apply
function Animal(name,age){
this.name = name;
this.age = age;
this.showName = function(){
console.log(this.name)
};
this.showAge = function(){
console.log(this.age)
};
}
function NewAnimal(name,age){
Animal.apply(this,[name,age])
}
var dog = new NewAnimal('小狗',6)
dog.showName()//小狗
dog.showAge()//6
call
function Animal(name,age){
this.name = name;
this.age = age;
this.showName = function(){
console.log(this.name)
};
this.showAge = function(){
console.log(this.age)
};
}
function NewAnimal(name,age){
Animal.call(this,name,age)
}
var dog = new NewAnimal('小狗',6)
dog.showName()//小狗
dog.showAge()//6
總結:
Animal.apply(NewAnimal, [參數1,參數2...]) Animal 爲即將被借用的對象 NewAnimal 爲借用者 後面的數組表明方法內部傳入的參數
Animal.call(NewAnimal, 參數1,參數2....) Animal 爲即將被借用的對象 NewAnimal 爲借用者 後面的參數123爲方法內部傳入的參數
兩個實現的效果都同樣,都是改變了this的指向,可是它們的傳參方式不同