剛剛接觸到apply和call方法時,對他們兩個的理解十分的模糊,最近在聯繫的過程中對apply和call有了更清晰的理解了,我把我對這個問題的理解記錄在這裏,如果有什麼不對的或者說的不清楚的地方還請大家指出,謝謝
1.apply
function Fruit(season, time, weight){
this.season = season;
this.time = time;
this.weight = weight;
this.showMessage = function(){
console.log(this.season);
console.log(this.time);
console.log(this.weight);
}
}
function Apple(season, time, weight, size){
Fruit.apply(this, arguments);
this.size = size;
this.showMessage = function(){
console.log(this.season);
console.log(this.time);
console.log(this.weight);
console.log(this.size);
}
}
var grape = new Fruit('spring', 'June', 34);
grape.showMessage();
console.log('\n');
var apple = new Apple('spring', 'September', 44, 'big');
apple.showMessage();
結果:2.call
function Fruit(season, time, weight){
this.season = season;
this.time = time;
this.weight = weight;
this.showMessage = function(){
console.log(this.season);
console.log(this.time);
console.log(this.weight);
}
}
function Apple(season, time, size){
Fruit.call(this, season, time, size);
this.size = size;
this.showMessage = function(){
console.log(this.season);
console.log(this.time);
console.log(this.size);
}
}
var grape = new Fruit('spring', 'June', 34);
grape.showMessage();
console.log('\n');
var apple = new Apple('spring', 333, 'small');
apple.showMessage();