js继承方式
原型继承
将子构造函数的prototype指向父构造函数的实例达到继承的目的;
function Person(name){
this.name = name;
this.country='china';
}
Person.prototype.play = function(){
}
function Child(age){
this.age = age;
}
Child.prototype = new Person();
缺点:
创建子类实例时,但是无法给父构造函数传参来自原型对象的引用属性是所有实例共享的
构造函数继承
在子类构造函数中调用父类构造函数
function Person(name){
this.name = name;
this.country='china';
}
Person.prototype.play = function(){
}
function Child(name,age){
this.age = age;
Person.call(this,name)
}
var obj = new Child('小明',16);
缺点:
- 当于每个实例都拷贝了一份父类的方法,占用内存大
不能继承原型属性/方法,只能继承父类的实例属性和方法
组合式继承
使用原型链实现对原型属性和方法的继承,通过借用构造函数实现对实例属性的继承
function Person(name){
this.name = name;
this.country='china';
}
Person.prototype.play = function(){
}
function Child(name,age){
Person.call(this,name);
this.age = age;
}
Child.prototype = new Person();
缺点:
会调用两次父类构造函数
浙公网安备 33010602011771号