call、apply方法
作用:改变this指向
区别:传参列表不同
我们通过一个实际案例来看
function Father(name, age, hobby) {
this.name = name;
this.age = age;
this.hobby = hobby;
}
function Son(name, age, hobby, grade) {
Father.call(this, name, age, hobby);
this.grade = grade;
}
var son = new Son("xiaozhuan", 13, "football", "2000");
call和apply还有一种引用:假设一个对象a中有一个方法b,还有一个c对象a.b.call(c); 意思是使c对象调用a中的b方法。apply类推一样的,当我们改变改变this指向时放入call括号内还可以放入调用方法的参数,看下面例子:
var arr = [1,2,3,4,5,6,7]
var arr1 = Array.prototype.slice.call(arr, 0, 3);
console.log(arr1);
圣杯模式继承
Father.prototype.hobby="football";
function Father(age) {
this.age = age;
}
function Son(name){
this.name = name;
}
function inherit (a,b) {
function F(){};
F.prototype = a.prototype;
b.prototype = new F();
b.prototype.constuctor=b;
}
inherit(Father, Son);
var father =new Father(31);
var son=new Son("xiaoli");
这样我们可以做到使对象通用一个原型来继承属性。