1. 程式人生 > >JS中的call、apply、bind方法詳解

JS中的call、apply、bind方法詳解

面試 glob ble ole 內部 修改 sta illegal 解決

bind 是返回對應函數,便於稍後調用;apply 、call 則是立即調用 。

apply、call

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

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

但是如果我們有一個對象banana= {color : "yellow"} ,我們不想對它重新定義 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 是為了動態改變 this 而出現的,當一個 object 沒有某個方法(本栗子中banana沒有say方法),但是其他的有(本栗子中apple有say方法),我們可以借助call或apply用其它對象的方法來操作。

apply、call 區別

對於 apply、call 二者而言,作用完全一樣,只是接受參數的方式不太一樣。例如,有一個函數定義如下:

var func = function(arg1, arg2) {
     
};

就可以通過如下方式來調用:

func.call(this
, arg1, arg2); func.apply(this, [arg1, arg2])

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

apply、call實例

數組之間追加

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] 

獲取數組中的最大值和最小值

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 使用其方法。

驗證是否是數組(前提是toString()方法沒有被重寫過)

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

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

var domNodes = Array.prototype.slice.call(document.getElementsByTagName("*"));

Javascript中存在一種名為偽數組的對象結構。比較特別的是 arguments 對象,還有像調用 getElementsByTagName , document.childNodes 之類的,它們返回NodeList對象都屬於偽數組。不能應用 Array下的 push , pop 等方法。
但是我們能通過 Array.prototype.slice.call 轉換為真正的數組的帶有 length 屬性的對象,這樣 domNodes 就可以應用 Array 下的所有方法了。

面試題

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

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

上面方法可以解決最基本的需求,但是當傳入參數的個數是不確定的時候,上面的方法就失效了,這個時候就可以考慮使用 apply 或者 call,註意這裏傳入多少個參數是不確定的,所以使用apply是最好的,方法如下:

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

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

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

該怎麽做比較優雅呢?這個時候需要想到arguments參數是個偽數組,通過 Array.prototype.slice.call 轉化為標準數組,再使用數組方法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");

結果:Uncaught TypeError: Illegal invocation
altwrite()函數改變this的指向global或window對象,導致執行時提示非法調用異常,正確的方案就是使用bind()方法:

altwrite.bind(document)("hello")

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

altwrite.call(document, "hello")

綁定函數

bind()最簡單的用法是創建一個函數,使這個函數不論怎麽調用都有同樣的this值。常見的錯誤就像上面的例子一樣,將方法從對象中拿出來,然後調用,並且希望this指向原來的對象。如果不做特殊處理,一般會丟失原來的對象。使用bind()方法能夠很漂亮的解決這個問題:

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

mymodule.getNum(); // 81

var getNum = mymodule.getNum;
getNum(); // 9, 因為在這個例子中,"this"指向全局對象

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

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

MDN的解釋是:bind()方法會創建一個新函數,稱為綁定函數,當調用這個綁定函數時,綁定函數會以創建它時傳入 bind()方法的第一個參數作為 this,傳入 bind() 方法的第二個以及以後的參數加上綁定函數運行時本身的參數按照順序作為原函數的參數來調用原函數。

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

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

由於 Javascript 特有的機制,上下文環境在 eventBind:function(){ } 過渡到 $(‘.someClass‘).on(‘click‘,function(event) { }) 發生了改變,上述使用變量保存 this 這些方式都是有用的,也沒有什麽問題。當然使用 bind() 可以更加優雅的解決這個問題:

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

在上述代碼裏,bind() 創建了一個函數,當這個click事件綁定在被調用的時候,它的 this 關鍵詞會被設置成被傳入的值(這裏指調用bind()時傳入的參數)。因此,這裏我們傳入想要的上下文 this(其實就是 foo ),到 bind() 函數中。然後,當回調函數被執行的時候, this 便指向 foo 對象。再來一個簡單的栗子:

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

這裏我們創建了一個新的函數 func,當使用 bind() 創建一個綁定函數之後,它被執行的時候,它的 this 會被設置成 foo , 而不是像我們調用 bar() 時的全局作用域。

偏函數(Partial Functions)

Partial Functions也叫Partial Applications,這裏截取一段關於偏函數的定義:

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()我們設定函數的預定義參數,然後調用的時候傳入其他參數即可:

function list() {
  return Array.prototype.slice.call(arguments);
}

var list1 = list(1, 2, 3); // [1, 2, 3]

// 預定義參數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秒後調用declare函數
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 朵花瓣!

註意:對於事件處理函數和setInterval方法也可以使用上面的方法

綁定函數作為構造函數

綁定函數也適用於使用new操作符來構造目標函數的實例。當使用綁定函數來構造實例,註意:this會被忽略,但是傳入的參數仍然可用。

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*/);
// 實現中的例子不支持,
// 原生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值的函數創造捷徑。

例如要將一個類數組對象轉換為真正的數組,可能的例子如下:

var slice = Array.prototype.slice;

// ...

slice.call(arguments);

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

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

// ...

slice(arguments);

實現

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

首先我們可以通過給目標函數指定作用域來簡單實現bind()方法:

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

考慮到函數柯裏化的情況,我們可以構建一個更加健壯的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()方法可以綁定對象,也支持在綁定的時候傳參。

繼續,Javascript的函數還可以作為構造函數,那麽綁定後的函數用這種方式調用時,情況就比較微妙了,需要涉及到原型鏈的傳遞:

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》一書中對bind()的實現:通過設置一個中轉構造函數F,使綁定後的函數與調用bind()的函數處於同一原型鏈上,用new操作符調用綁定後的函數,返回的對象也能正常使用instanceof,因此這是最嚴謹的bind()實現。

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

Function.prototype.bind = function (oThis) {
    if (typeof this !== "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 () {
          return fToBind.apply(
              this instanceof fNOP && oThis ? this : oThis || window,
              aArgs.concat(Array.prototype.slice.call(arguments))
          );
        };

    fNOP.prototype = this.prototype;
    fBound.prototype = new fNOP();

    return fBound;
  };

有個有趣的問題,如果連續 bind() 兩次,亦或者是連續 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() 的實現,相當於使用函數在內部包了一個 call / apply ,第二次 bind() 相當於再包住第一次 bind() ,故第二次以後的 bind 是無法生效的。

apply、call、bind比較

那麽 apply、call、bind 三者相比較,之間又有什麽異同呢?何時使用 apply、call,何時使用 bind 呢。簡單的一個栗子:

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

三個輸出的都是81,但是註意看使用 bind() 方法的,他後面多了對括號。

也就是說,區別是,當你希望改變上下文環境之後並非立即執行,而是回調執行的時候,使用 bind() 方法。而 apply/call 則會立即執行函數。

再總結一下:

  • apply 、 call 、bind 三者都是用來改變函數的this對象的指向的;
  • apply 、 call 、bind 三者第一個參數都是this要指向的對象,也就是想指定的上下文;
  • apply 、 call 、bind 三者都可以利用後續參數傳參;
  • bind 是返回對應函數,便於稍後調用;apply 、call 則是立即調用 。

JS中的call、apply、bind方法詳解