call、apply、bind

this指向

在 ES5 中,其實(shí) this 的指向,始終堅(jiān)持一個(gè)原理: this 永遠(yuǎn)指向最后調(diào)用它的那個(gè)對(duì)象(也就是說:this取什么值是在函數(shù)執(zhí)行時(shí)確定的,不是在函數(shù)定義時(shí)確定的)

看個(gè)例子:

var name = "如來佛祖";
function a() {
  var name = "孫悟空";
  console.log(this.name); // 如來佛祖
  console.log("inner:" + this); //inner:[object Window]
}
a();
console.log("outer:" + this); //outer:[object Window]

像上面說的 this取什么值是在函數(shù)執(zhí)行時(shí)確定的,最后k看調(diào)用 a 的地方 a(),前面沒有調(diào)用的對(duì)象那么就是全局對(duì)象 window,這就相當(dāng)于是 window.a()這里我們沒有使用嚴(yán)格模式,如果使用嚴(yán)格模式的話,全局對(duì)象就是 undefined,那么就會(huì)報(bào)錯(cuò) Uncaught TypeError: Cannot read property 'name' of undefined。

再來一個(gè):

var name = "如來佛祖";
var a = {
  name: "孫悟空",
  fn: function() {
    name="豬八戒";
    console.log(this.name); //孫悟空
  }
};
window.a.fn();

為什么,這里會(huì)是孫悟空,而不是豬八戒呢,或者為什么不是如來佛祖呢,因?yàn)槿缟厦娴哪蔷湓挘簍his取什么值是在函數(shù)執(zhí)行時(shí)確定的,因?yàn)?,window.a.fn()就表示,調(diào)用 fn 的是 a 對(duì)象,也就是說 fn 的內(nèi)部的 this 是對(duì)象 a,所以name是孫悟空。

改變this 的指向

使用 ES6 的箭頭函數(shù)
在函數(shù)內(nèi)部使用 _this = this
使用 apply、call、bind

1、使用 ES6 的箭頭函數(shù)

    var name = "如來佛祖";
    var a = {
      name: "孫悟空",
      func1: function() {
        console.log(this.name);
      },
      func2: function() {
        setTimeout(() => {
          this.func1();
        }, 100);
      }
    };
    a.func2(); //孫悟空

2、在函數(shù)內(nèi)部使用 _this = this

    var name = "如來佛祖";
    var a = {
      name: "孫悟空",
      func1: function() {
        console.log(this.name);
      },
      func2: function() {
        var _this = this;
        setTimeout(function() {
          _this.func1();
        }, 100);
      }
    };
    a.func2(); //孫悟空

3、使用 apply、call、bind

apply、call、bind

1、apply 、 call 、bind 三者都是用來改變函數(shù)的this對(duì)象的指向的;
2、apply 、 call 、bind 三者第一個(gè)參數(shù)都是this要指向的對(duì)象,也就是想指定的上下文;
3、apply 、 call 、bind 三者都可以利用后續(xù)參數(shù)傳參;
4、bind是返回對(duì)應(yīng)函數(shù),便于稍后調(diào)用;apply、call則是立即調(diào)用 。
5、call 需要把參數(shù)按順序傳遞進(jìn)去,而 apply 則是把參數(shù)放在數(shù)組里。
6、某個(gè)函數(shù)的參數(shù)是明確知道數(shù)量時(shí)用 call ; 而不確定的時(shí)候用 apply,然后把參數(shù) push進(jìn)數(shù)組傳遞進(jìn)去。當(dāng)參數(shù)數(shù)量不確定時(shí),函數(shù)內(nèi)部也可以通過 arguments 這個(gè)數(shù)組來遍歷所有的參數(shù)
7、func.call(this, arg1, arg2);
8、func.apply(this, [arg1, arg2])

在 javascript 中,call 和 apply 都是為了改變某個(gè)函數(shù)運(yùn)行時(shí)的上下文(context)而存在的,換句話說,就是為了改變函數(shù)體內(nèi)部 this 的指向。
JavaScript 的一大特點(diǎn)是,函數(shù)存在「定義時(shí)上下文」和「運(yùn)行時(shí)上下文」以及「上下文是可以改變的」這樣的概念。

function fruits() {}

fruits.prototype = {
    color: "red",
    say: function() {
        console.log("My color is " + this.color);
    }
} var apple = new fruits;
apple.say(); //My color is red

但是如果我們有一個(gè)對(duì)象banana= {color : "yellow"} ,我們不想對(duì)它重新定義 say 方法,那么我們可以通過 call 或 apply 用 apple 的 say 方法:

banana = {
    color: "yellow" }
apple.say.call(banana); //My color is yellow
apple.say.apply(banana);    //My color is yellow

所以,可以看出 call 和 apply 是為了動(dòng)態(tài)改變 this 而出現(xiàn)的,當(dāng)一個(gè) object 沒有某個(gè)方法(本栗子中banana沒有say方法),但是其他的有(本栗子中apple有say方法),我們可以借助call或apply用其它對(duì)象的方法來操作。

apply、call 區(qū)別

對(duì)于 apply、call 二者而言,作用完全一樣,只是接受參數(shù)的方式不太一樣。例如,有一個(gè)函數(shù)定義如下:

var func = function(arg1, arg2) {

};

就可以通過如下方式來調(diào)用:

func.call(this, arg1, arg2);
func.apply(this, [arg1, arg2])</pre>

其中 this 是你想指定的上下文,他可以是任何一個(gè) JavaScript 對(duì)象(JavaScript 中一切皆對(duì)象),call 需要把參數(shù)按順序傳遞進(jìn)去,而 apply 則是把參數(shù)放在數(shù)組里?! ?br> 為了鞏固加深記憶,下面列舉一些常用用法:

apply、call實(shí)例

數(shù)組之間追加

var array1 = [12 , "foo" , {name:"Joe"} , -2458];
 var array2 = ["Doe" , 555 , 100]; 
Array.prototype.push.apply(array1, array2); // array1 值為  [12 , "foo" , {name:"Joe"} , -2458 , "Doe" , 555 , 100] 

獲取數(shù)組中的最大值和最小值

var  numbers = [5, 458 , 120 , -215 ]; 
var maxInNumbers = Math.max.apply(Math, numbers),   //458
    maxInNumbers = Math.max.call(Math,5, 458 , 120 , -215); //458

number 本身沒有 max 方法,但是 Math 有,我們就可以借助 call 或者 apply 使用其方法。

驗(yàn)證是否是數(shù)組(前提是toString()方法沒有被重寫過)

functionisArray(obj){ return Object.prototype.toString.call(obj) === '[object Array]' ;
}

類(偽)數(shù)組使用數(shù)組方法

var domNodes = Array.prototype.slice.call(document.getElementsByTagName("*"));</pre>

Javascript中存在一種名為偽數(shù)組的對(duì)象結(jié)構(gòu)。比較特別的是 arguments 對(duì)象,還有像調(diào)用 getElementsByTagName , document.childNodes 之類的,它們返回NodeList對(duì)象都屬于偽數(shù)組。不能應(yīng)用 Array下的 push , pop 等方法。
但是我們能通過 Array.prototype.slice.call 轉(zhuǎn)換為真正的數(shù)組的帶有 length 屬性的對(duì)象,這樣 domNodes 就可以應(yīng)用 Array 下的所有方法了。

面試題

定義一個(gè) log 方法,讓它可以代理 console.log 方法,常見的解決方法是:

function log(msg){
  console.log(msg);
}
log(1);    //1
log(1,2);    //1

上面方法可以解決最基本的需求,但是當(dāng)傳入?yún)?shù)的個(gè)數(shù)是不確定的時(shí)候,上面的方法就失效了,這個(gè)時(shí)候就可以考慮使用 apply 或者 call,注意這里傳入多少個(gè)參數(shù)是不確定的,所以使用apply是最好的,方法如下:

function log(){
  console.log.apply(console, arguments);
};
log(1);    //1
log(1,2);    //1 2

接下來的要求是給每一個(gè) log 消息添加一個(gè)"(app)"的前輟,比如:

log("hello world"); //(app)hello world

該怎么做比較優(yōu)雅呢?這個(gè)時(shí)候需要想到arguments參數(shù)是個(gè)偽數(shù)組,通過 Array.prototype.slice.call 轉(zhuǎn)化為標(biāo)準(zhǔn)數(shù)組,再使用數(shù)組方法unshift,像這樣:

function log(){ var args = Array.prototype.slice.call(arguments);
  args.unshift('(app)');

  console.log.apply(console, args);
};

bind

在討論bind()方法之前我們先來看一道題目:

var altwrite = document.write;
altwrite("hello");

結(jié)果:Uncaught TypeError: Illegal invocation
altwrite()函數(shù)改變this的指向global或window對(duì)象,導(dǎo)致執(zhí)行時(shí)提示非法調(diào)用異常,正確的方案就是使用bind()方法:

altwrite.bind(document)("hello")</pre>

當(dāng)然也可以使用call()方法:

altwrite.call(document, "hello")</pre>

綁定函數(shù)

bind()最簡(jiǎn)單的用法是創(chuàng)建一個(gè)函數(shù),使這個(gè)函數(shù)不論怎么調(diào)用都有同樣的this值。常見的錯(cuò)誤就像上面的例子一樣,將方法從對(duì)象中拿出來,然后調(diào)用,并且希望this指向原來的對(duì)象。如果不做特殊處理,一般會(huì)丟失原來的對(duì)象。使用bind()方法能夠很漂亮的解決這個(gè)問題:

this.num = 9;
var mymodule = {
  num: 81,
  getNum: function() { 
    console.log(this.num);
  }
};

mymodule.getNum(); // 81

var getNum = mymodule.getNum;
getNum(); // 9, 因?yàn)樵谶@個(gè)例子中,"this"指向全局對(duì)象

var boundGetNum = getNum.bind(mymodule);
boundGetNum(); // 81

bind() 方法與 apply 和 call 很相似,也是可以改變函數(shù)體內(nèi) this 的指向。

MDN的解釋是:bind()方法會(huì)創(chuàng)建一個(gè)新函數(shù),稱為綁定函數(shù),當(dāng)調(diào)用這個(gè)綁定函數(shù)時(shí),綁定函數(shù)會(huì)以創(chuàng)建它時(shí)傳入 bind()方法的第一個(gè)參數(shù)作為 this,傳入 bind() 方法的第二個(gè)以及以后的參數(shù)加上綁定函數(shù)運(yùn)行時(shí)本身的參數(shù)按照順序作為原函數(shù)的參數(shù)來調(diào)用原函數(shù)。

直接來看看具體如何使用,在常見的單體模式中,通常我們會(huì)使用 _this , that , self 等保存 this ,這樣我們可以在改變了上下文之后繼續(xù)引用到它。 像這樣:

var foo = {
    bar : 1,
    eventBind: function(){ var _this = this;
        $('.someClass').on('click',function(event) { /* Act on the event */ console.log(_this.bar); //1
 });
    }
}

由于 Javascript 特有的機(jī)制,上下文環(huán)境在 eventBind:function(){ } 過渡到 $('.someClass').on('click',function(event) { }) 發(fā)生了改變,上述使用變量保存 this 這些方式都是有用的,也沒有什么問題。當(dāng)然使用 bind() 可以更加優(yōu)雅的解決這個(gè)問題:

var foo = {
    bar : 1,
    eventBind: function(){
        $('.someClass').on('click',function(event) { /* Act on the event */ console.log(this.bar);      //1
        }.bind(this));
    }
}

在上述代碼里,bind() 創(chuàng)建了一個(gè)函數(shù),當(dāng)這個(gè)click事件綁定在被調(diào)用的時(shí)候,它的 this 關(guān)鍵詞會(huì)被設(shè)置成被傳入的值(這里指調(diào)用bind()時(shí)傳入的參數(shù))。因此,這里我們傳入想要的上下文 this(其實(shí)就是 foo ),到 bind() 函數(shù)中。然后,當(dāng)回調(diào)函數(shù)被執(zhí)行的時(shí)候, this 便指向 foo 對(duì)象。再來一個(gè)簡(jiǎn)單的栗子:

var bar = function(){
console.log(this.x);
} 
var foo = {
x:3 }
bar(); // undefined
var func = bar.bind(foo);
func(); // 3

這里我們創(chuàng)建了一個(gè)新的函數(shù) func,當(dāng)使用 bind() 創(chuàng)建一個(gè)綁定函數(shù)之后,它被執(zhí)行的時(shí)候,它的 this 會(huì)被設(shè)置成 foo , 而不是像我們調(diào)用 bar() 時(shí)的全局作用域。

偏函數(shù)(Partial Functions)

Partial Functions也叫Partial Applications,這里截取一段關(guān)于偏函數(shù)的定義:

Partial application can be described as taking a function that accepts some number of arguments, binding values to one or more of those arguments, and returning a new function that only accepts the remaining, un-bound arguments.

bind()的另一個(gè)最簡(jiǎn)單的用法是使一個(gè)函數(shù)擁有預(yù)設(shè)的初始參數(shù)。只要將這些參數(shù)(如果有的話)作為bind()的參數(shù)寫在this后面。當(dāng)綁定函數(shù)被調(diào)用時(shí),這些參數(shù)會(huì)被插入到目標(biāo)函數(shù)的參數(shù)列表的開始位置,傳遞給綁定函數(shù)的參數(shù)會(huì)跟在它們后面。

function list() { return Array.prototype.slice.call(arguments);
} 
var list1 = list(1, 2, 3); // [1, 2, 3]

// 預(yù)定義參數(shù)37
var leadingThirtysevenList = list.bind(undefined, 37); 
var list2 = leadingThirtysevenList(); // [37]
var list3 = leadingThirtysevenList(1, 2, 3); // [37, 1, 2, 3]

和setTimeout一起使用

function Bloomer() { this.petalCount = Math.ceil(Math.random() * 12) + 1;
} // 1秒后調(diào)用declare函數(shù)
Bloomer.prototype.bloom = function() {
  window.setTimeout(this.declare.bind(this), 100);
};

Bloomer.prototype.declare = function() {
  console.log('我有 ' + this.petalCount + ' 朵花瓣!');
}; 
var bloo = new Bloomer();
bloo.bloom(); //我有 5 朵花瓣!

注意:對(duì)于事件處理函數(shù)和setInterval方法也可以使用上面的方法

綁定函數(shù)作為構(gòu)造函數(shù)

綁定函數(shù)也適用于使用new操作符來構(gòu)造目標(biāo)函數(shù)的實(shí)例。當(dāng)使用綁定函數(shù)來構(gòu)造實(shí)例,注意:this會(huì)被忽略,但是傳入的參數(shù)仍然可用。

function Point(x, y) { 
    this.x = x; this.y = y;
}

Point.prototype.toString = function() { 
    console.log(this.x + ',' + this.y);
}; 
var p = new Point(1, 2);
p.toString(); // '1,2'

var emptyObj = {}; 
var YAxisPoint = Point.bind(emptyObj, 0/*x*/); // 實(shí)現(xiàn)中的例子不支持, // 原生bind支持:
var YAxisPoint = Point.bind(null, 0/*x*/); var axisPoint = new YAxisPoint(5);
axisPoint.toString(); // '0,5'
axisPoint instanceof Point; // true
axisPoint instanceof YAxisPoint; // true
new Point(17, 42) instanceof YAxisPoint; // true

捷徑

bind()也可以為需要特定this值的函數(shù)創(chuàng)造捷徑。

例如要將一個(gè)類數(shù)組對(duì)象轉(zhuǎn)換為真正的數(shù)組,可能的例子如下:

var slice = Array.prototype.slice; // ...
slice.call(arguments);

如果使用bind()的話,情況變得更簡(jiǎn)單:

var unboundSlice = Array.prototype.slice; 
var slice = Function.prototype.call.bind(unboundSlice); // ...
slice(arguments);

bind實(shí)現(xiàn)

上面的幾個(gè)小節(jié)可以看出bind()有很多的使用場(chǎng)景,但是bind()函數(shù)是在 ECMA-262 第五版才被加入;它可能無法在所有瀏覽器上運(yùn)行。這就需要我們自己實(shí)現(xiàn)bind()函數(shù)了。

首先我們可以通過給目標(biāo)函數(shù)指定作用域來簡(jiǎn)單實(shí)現(xiàn)bind()方法:

Function.prototype.bind = function(context){
    self = this;  //保存this,即調(diào)用bind方法的目標(biāo)函數(shù)
    return function(){ 
        return self.apply(context,arguments);
  };
};

考慮到函數(shù)柯里化的情況,我們可以構(gòu)建一個(gè)更加健壯的bind():

Function.prototype.bind = function(context){ 
    var args = Array.prototype.slice.call(arguments, 1),
    self = this; 
    return function(){ 
        var innerArgs = Array.prototype.slice.call(arguments); 
        var finalArgs = args.concat(innerArgs); 
        return self.apply(context,finalArgs);
  };
};

這次的bind()方法可以綁定對(duì)象,也支持在綁定的時(shí)候傳參。

繼續(xù),Javascript的函數(shù)還可以作為構(gòu)造函數(shù),那么綁定后的函數(shù)用這種方式調(diào)用時(shí),情況就比較微妙了,需要涉及到原型鏈的傳遞:

Function.prototype.bind = function(context){ 
        var args = Array.prototype.slice(arguments, 1),
        F = function(){},
        self = this,
        bound = function(){ 
              var innerArgs = Array.prototype.slice.call(arguments); 
              var finalArgs = args.concat(innerArgs); 
              return self.apply((this instanceof F ? this : context), finalArgs);
        };

        F.prototype = self.prototype;
        bound.prototype = new F(); return bound;
};

這是《JavaScript Web Application》一書中對(duì)bind()的實(shí)現(xiàn):通過設(shè)置一個(gè)中轉(zhuǎn)構(gòu)造函數(shù)F,使綁定后的函數(shù)與調(diào)用bind()的函數(shù)處于同一原型鏈上,用new操作符調(diào)用綁定后的函數(shù),返回的對(duì)象也能正常使用instanceof,因此這是最嚴(yán)謹(jǐn)?shù)腷ind()實(shí)現(xiàn)。

對(duì)于為了在瀏覽器中能支持bind()函數(shù),只需要對(duì)上述函數(shù)稍微修改即可:

if (!Function.prototype.bind) {
      Function.prototype.bind = function(oThis) { 
            if (typeof this !== 'function') { // closest thing possible to the ECMAScript 5
            // internal IsCallable function
             throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
      } 
       var aArgs   = Array.prototype.slice.call(arguments, 1),
       fToBind = this,
       fNOP = function() {},
       fBound = function() { 
        // this instanceof fBound === true時(shí),說明返回的fBound被當(dāng)做new的構(gòu)造函數(shù)調(diào)用
              return fToBind.apply(this instanceof fBound 
                        ? this : oThis, // 獲取調(diào)用時(shí)(fBound)的傳參.bind 返回的函數(shù)入?yún)⑼沁@么傳遞的
                         aArgs.concat(Array.prototype.slice.call(arguments)));
        }; // 維護(hù)原型關(guān)系
        if (this.prototype) { // Function.prototype doesn't have a prototype property
              fNOP.prototype = this.prototype; 
         } // 下行的代碼使fBound.prototype是fNOP的實(shí)例,因此
        // 返回的fBound若作為new的構(gòu)造函數(shù),new生成的新對(duì)象作為this傳入fBound,新對(duì)象的__proto__就是fNOP的實(shí)例
      fBound.prototype = new fNOP(); return fBound;
  };
}

下面這個(gè)便于理解:

Function.prototype.bind = function (that) {
        if (typeof this !== 'function') {
            throw new TypeError('Error')
        }
        const args = [...arguments].slice(1);
        const fn = this;
        return function () {
            fn.apply(that)
        };
        // 返回一個(gè)函數(shù)
        return function F() {
            // 因?yàn)榉祷亓艘粋€(gè)函數(shù),如果是new的話this就要指向新創(chuàng)建的對(duì)象了
            if (this instanceof F) {
                return new fn(...args, ...arguments)
            }
            return fn.apply(that, args.concat(...arguments))
        }
    };

有個(gè)有趣的問題,如果連續(xù) bind() 兩次,亦或者是連續(xù) bind() 三次那么輸出的值是什么呢?像這樣:

var bar = function(){
    console.log(this.x);
} var foo = {
    x:3 } var sed = {
    x:4 } var func = bar.bind(foo).bind(sed);
func(); //?

var fiv = {
    x:5 } var func = bar.bind(foo).bind(sed).bind(fiv);
func(); //?

答案是,兩次都仍將輸出 3 ,而非期待中的 4 和 5 。原因是,在Javascript中,多次 bind() 是無效的。更深層次的原因, bind() 的實(shí)現(xiàn),相當(dāng)于使用函數(shù)在內(nèi)部包了一個(gè) call / apply ,第二次 bind() 相當(dāng)于再包住第一次 bind() ,故第二次以后的 bind 是無法生效的。

apply、call、bind比較

那么 apply、call、bind 三者相比較,之間又有什么異同呢?何時(shí)使用 apply、call,何時(shí)使用 bind 呢。簡(jiǎn)單的一個(gè)栗子:

var obj = {
    x: 81,
}; 
var foo = {
    getX: function() { return this.x;
    }
}

console.log(foo.getX.bind(obj)()); //81
console.log(foo.getX.call(obj));    //81
console.log(foo.getX.apply(obj));   //81</pre>

三個(gè)輸出的都是81,但是注意看使用 bind() 方法的,他后面多了對(duì)括號(hào)。

也就是說,區(qū)別是,當(dāng)你希望改變上下文環(huán)境之后并非立即執(zhí)行,而是回調(diào)執(zhí)行的時(shí)候,使用 bind() 方法。而 apply/call 則會(huì)立即執(zhí)行函數(shù)。

apply、call實(shí)現(xiàn)

apply實(shí)現(xiàn)如下:

const obj = {
    name:'joy'
};

function getName(a,b){
    console.log(this.name,a,b);
}

Function.prototype.newApply = function (that,arg) {
    if(typeof this !== 'function'){
        throw this+'is not a function'
    }
    that = that || window; //因?yàn)榈谝粋€(gè)參數(shù)如果不傳就會(huì)綁定到window上面
    arg = arg || [];
    that.myFn = this;
    const result = that.myFn(...arg); //解構(gòu)賦值把參數(shù)傳進(jìn)來,先把結(jié)果存起來
    delete that.myFn; //再刪除,否則就有副作用了
    return result;
};

getName.newApply(obj,[1,2]); // joy

call實(shí)現(xiàn)如下:

const obj = {
    name:'joy'
};

function getName(a,b){
    console.log(this.name,a,b);
}

  Function.prototype.newCall = function (that, ...arg) {
            if (typeof this !== 'function') {
                throw this + 'is not a function'
            }
            that = that || window; //因?yàn)榈谝粋€(gè)參數(shù)如果不傳就會(huì)綁定到window上面
            that.myFn = this;
            const result = that.myFn(...arg); //解構(gòu)賦值把參數(shù)傳進(jìn)來,先把結(jié)果存起來
            delete that.myFn; //再刪除,否則就有副作用了
            return result;
        };

        getName.newApply(obj, 1, 2); // joy 1 2

再總結(jié)一下:

  • apply 、 call 、bind 三者都是用來改變函數(shù)的this對(duì)象的指向的;
  • apply 、 call 、bind 三者第一個(gè)參數(shù)都是this要指向的對(duì)象,也就是想指定的上下文;
  • apply 、 call 、bind 三者都可以利用后續(xù)參數(shù)傳參;
  • bind 是返回對(duì)應(yīng)函數(shù),便于稍后調(diào)用;apply 、call 則是立即調(diào)用 。

bind詳細(xì)參考地址:《MDN:Function.prototype.bind()》

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容