1痊剖、call有兩個(gè)妙用:
1: 繼承。(不太喜歡這種繼承方式佛析。)
2: 修改函數(shù)運(yùn)行時(shí)的this指針。
這里引用《javascript權(quán)威指南》對(duì)call的描述
image.png
注意紅色框中的部分脉让,f.call(o)其原理就是先通過 o.m = f 將 f作為o的某個(gè)臨時(shí)屬性m存儲(chǔ)骗奖,然后執(zhí)行m贷痪,執(zhí)行完畢后將m屬性刪除惰聂。
function f() {
var a = "name";
this.b = "test1";
this.add = function() {
return "add"
}
}
function o() {
this.c = "c";
}
f.call(o) 其實(shí)相當(dāng)于:
function o() {
this.c = "c";
var a = "name";
this.b = "test1";
this.add = function() {
return "add"
}
}
說白了城侧,就是把f的方法在o中走一遍易遣,但不做保存。既然不做保存嫌佑,那么如何通過call實(shí)現(xiàn)繼承和修改函數(shù)運(yùn)行時(shí)的this指針等妙用豆茫?關(guān)鍵在于this,對(duì)屋摇,關(guān)鍵還是在于this的作用域揩魂。在之前的文章反復(fù)說過,this的作用域不是定義它的函數(shù)的作用域炮温,而是執(zhí)行時(shí)的作用域火脉。
image.png
第一個(gè)中直接調(diào)用fn方法,其中因?yàn)闆]有定義函數(shù)作用域柒啤,輸出的this表示window對(duì)象倦挂,即全局對(duì)象。而第二個(gè)中通過fn.call(array[index] , index , array[index] )將fn方法放到array[index]作用域中執(zhí)行担巩,輸出的this表示的是array[index]對(duì)象方援。
//實(shí)現(xiàn)each方法封裝
var each = function(arr,fn) {
for (var i=0; i<arr.length; i++){
fn.call(arr[i],i,arr[i]);
}
}
each([1,2,3,4],function(i,item){
console.log(this) //當(dāng)前this指向arr[i]
console.log(i) //上面?zhèn)鞯牡谝粋€(gè)參數(shù)i
console.log(item) //上面?zhèn)鞯亩€(gè)參數(shù)arr[i] 這里主要說明call的傳參方式
})