JavaScript中的apply和call

剛剛接觸到apply和call方法時,對他們兩個的理解十分的模糊,最近在聯繫的過程中對apply和call有了更清晰的理解了,我把我對這個問題的理解記錄在這裏,如果有什麼不對的或者說的不清楚的地方還請大家指出,謝謝


1.apply   

apply的語法:Function.apply(obj, args)
apply可以用另一個對象代替當前對象。
apply方法有兩個參數:
obj:這個對象將代替function裏的this對象
args:是一個數組,會作爲參數傳遞給function
如果沒有提供obj參數,那麼Global對象將作用於obj
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();
結果:


分析:
當一開始創建Apple類時,this指向的是Apple,後來程序運行到apply語句,this代替Fruit中的對象,即用Apple去執行Fruit的內容,這樣,Fruit類中的season,time,weight屬性就成功創建到了Apple類中。

2.call

call和apply意思一樣,除了參數列表的不同。
call的語法:Function(this,參數列表)
舉個例子,對鋼材的代碼稍加改動
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();




3.兩者之間的區別

用apply時,傳遞的參數爲arguments,參數類型爲數組,參數列表是一一對應的,也就是說arguments的前幾位和Fruit中的參數完全相同,而運用call方法時,參數是可以選擇的,我們可以根據需求來寫參數,在上面的例子中我們可以看到,我們所需要的參數只有season和call,在這種情況下,這種做法是十分靈活方便的。


發佈了34 篇原創文章 · 獲贊 3 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章