1. 借助call
function Parent(){
this.name='parent';
}
function Child(){
Parent.call(this);
this.type='child'
};
console.log(new Child);
// {name: "parent",type: "child"}
这样写的时候子类虽然能够拿到父类的属性值,但是问题是父类原型对象中一旦存在方法那么子类无法继承。
2. 借助原型链
function Parent() {
this.name='parent';
this.play= [1, 2, 3]
}
function Child() {
this.type='child';
}
Child.prototype=new Parent();
console.log(new Child());
// {type: "child",__proto__:Parent}
看似没有问题,父类的方法和属性都能够访问,但实际上有一个潜在的不足。
var s1=new Child();
var s2=new Child();
s1.play.push(4);
// console.log(s1.play);
// [1, 2, 3, 4]
// console.log(s2.play);
// [1, 2, 3, 4]
明明我只改变了s1的play属性,为什么s2也跟着变了呢?很简单,因为两个实例使用的是