1、构造函数继承
1 2 3 4 5 6 7 8 9 10 11 12 13 | function Animal(){ this.species = "动物"; } function Cat(name, color){ Animal.apply(this, arguments); this.name = name; this.color = color; } var cat1 = new Cat("大毛", "黄色"); console.log(cat1.species); // 动物 |
1.1、call与apply的区别
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | function Animal(name){ this.name = name; this.showName = function(){ console.log(this.name); } } function Cat(name){ Animal.call(this, name); // class.call(obj, argument1, argument2, ...) // Animal.apply(this, arguments); // class.apply(obj, arguments) } var cat = new Cat("黑猫警长"); cat.showName(); |
2、原型继承
1 2 3 4 5 6 7 8 9 10 11 12 13 | function Animal(){ this.species = "动物"; } function Cat(name, color){ this.name = name; this.color = color; } Cat.prototype = new Animal(); var cat1 = new Cat("大毛", "黄色"); console.log(cat1.species); // 动物 |
2.1 构造函数中使用原型继承需要用类(函数)名,不能用this
function Cat(name, color){
this.prototype = new Animal(); // 无效
Cat.prototype = new Animal(); // 有效
this.name = name;
this.color = color;
}
2.2 apply不能继承原型属性/方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | function Animal(name){ this.name = name; } // Animal.apply(this, arguments); 不能继承该方法 Animal.prototype.showName = function(){ console.log(this.name); } function Cat(name){ Animal.apply(this, arguments); } var cat = new Cat("黑猫警长"); cat.showName(); // TypeError: Object #<Cat> has no method 'showName' |
总结:如果使用class.apply/call继承,只在constructor中实现父类的属性和方法,不使用prototype;如果使用class.prototype = new parent_class()继承,则可以使用prototype定义属性和方法。