通過call或者apply可以實現函數里面this的改變,利用這一特點,可以實現繼承
代碼如下所示:
/*父類*/
function Parent(add,net,no,teacher) {
this.add = add;
this.net = net;
this.no = no;
this.teacher = teacher
}
/*子類*/
function Child(name,age,sex,id) {
this.name = name;
this.sex = sex;
this.age = age;
this.id = id;
Parent.call(this,"山東","www.baidu.com","1608","ccy"); //這個時候的Parent中的this已經被Child所代替
}
var child = new Child("fangMing","18","男","10086");
console.log(child.add)
如果想用apply方法,可以將注釋的一句改為Parent.apply(this,["山東","www.baidu.com","1608","ccy"]),兩者的用法是一樣的等效,唯一的區別就是
call后面跟的是有個一個一個單獨的數據,而apply需要把數據放在數組里面