实现继承的方式
- 原型继承
子构造函数.prototype = 父实例 (Child.prototype = new Father();
)
function Father(){
this.a = [1, 2, 3]
}
Father.prototype.aFun = function(){
console.log('a')
}
function Child() {
this.name = 'bb'
}
Child.prototype = new Father();
Child.prototype.bFun = function() {
conosle.log('b')
}
var child1 = new Child();
child1.aFun(); //a
child1.a;
缺点:
- 定义在父构造函数内的属性,每个父实例都会有各种的一份实例属性。子构造函数的原型是父构造函数的一个实例,每个子实例共享相同的原型上的属性。
- 无法从子构造函数向父构造函数传递参数
- 构造函数继承
function Father(name){
this.a = [1, 2, 3];
this.name = name;
}
function Child() {
Father.call(this, 'qi')
this.value = 'bb'
}
var child1 = new Child();
缺点: 无法共享原型对象上的方法
- 通过构造函数继承属性,通过原型链继承方法(应用广泛)
function Father(name){
this.a = [1, 2, 3];
this.name = name;
}
Father.prototype.aFun = function(){
console.log('a')
}
function Child() {
Father.call(this, 'qi')
this.value = 'bb'
}
Child.prototype = new Father();
Child.prototype.constructor = Child;
Child.prototype.bFun = function() {
conosle.log('b')
}
var child1 = new Child();
网友评论