js中的 call()、apply()、bind()

之前在 javascript this 相關(guān)總結(jié)一文中說要對call()、apply()、bind() 要再寫一篇總結(jié)詳談,今天把坑填起來。

先說call()和apply()

call() apply() 可以改變函數(shù)執(zhí)行上下文中 this 的指向。當某個方法并不存在于某個對象, 可以借助call()或apply()在該對象上調(diào)用該方法。

一個最簡單的例子

//有一個函數(shù)定義如下:
function sayHi( species,country) {
  console.log(`Hello I am ${species} ${this.name}, live in ${country}`);
}

//有一個對象pandaBob定義如下:
var pandaBob={name:'Bob'}

//對象pandaBob上并不存在sayHi(),但可借助call或apply在/pandaBob對象上調(diào)用sayHi()。
sayHi.call(pandaBob, 'panda', 'china');//Hello I am panda Bob, live in china
sayHi.apply(pandaBob, [ 'panda', 'china'])//Hello I am panda Bob, live in china

可以看到:對于 apply()、call() 二者而言,作用基本一樣,只是接受參數(shù)的方式不太相同。
兩者接收的第一個參數(shù)的作用都是指定要被調(diào)用的函數(shù) 運行時的 執(zhí)行上下文的this。

兩者的區(qū)別在于:

  • 借用call調(diào)用某方法時,該方法的參數(shù)會通過call()的第一個之后的參數(shù) 以若干個參數(shù)的列表的形式傳入。
  • 借用apply調(diào)用某方法時,該方法的參數(shù)會通過apply()的第二個參數(shù) 以一個包含多個參數(shù)的數(shù)組或類數(shù)組對象的形式傳入。

注意:通常多是以數(shù)組或 arguments這個類數(shù)組對象的形式傳入。事實上對其他類數(shù)組對象的支持是ES5 之后的事情了。也就是說ES5之前只能以數(shù)組或arguments的形式傳入。

正因這點不同兩者分別有各自更適合的應(yīng)用場景。

call() 的使用場景及例子:

參數(shù)數(shù)量明確或者不需要參數(shù)時用建議用 call ,這樣更簡高效。

舉幾個例子:

  1. 在繼承中使用call,調(diào)用父函數(shù)的構(gòu)造函數(shù)。(參數(shù)數(shù)量確定)
function Product(name, price) {
  this.name = name;
  this.price = price;

  if (price < 0) {
    throw RangeError('Cannot create product ' +this.name + ' with a negative price');
  }
}

function Food(caloriesPerGram,name, price) {

  Product.call(this, name, price); 
}
var cheese = new Food('feta', 5);

其實上例中的子類的構(gòu)造函數(shù) 如果不需要傳入更多的的參入(即caloriesPerGram)或者把額外的參數(shù)放在 name, price之后還可以這么用:

function Food(name, price,caloriesPerGram) {
  this.category = 'food';
  this.caloriesPerGram=caloriesPerGram;
  Product.apply(this, arguments); 
}

這種情況下用call()可以適應(yīng)更靈活的參數(shù)列表。

2.使用call方法調(diào)用匿名函數(shù)。(參數(shù)數(shù)量明確)

var animals = [
  {species: 'Lion', name: 'King'},
  {species: 'Whale', name: 'Fail'}
];

for (var i = 0; i < animals.length; i++) {
  (function (i) { 
    this.print = function () { 
      console.log('#' + i  + ' ' + this.species + ': ' + this.name); 
    } 
    this.print();
  }).call(animals[i], i);
}

3.安全的類型檢查(不需要參數(shù))

function isArray(value){
return Object.prototype.toString.call(value) == "[object Array]";
}

4.使用call方法調(diào)用函數(shù)并且指定上下文的'this'(不需要參數(shù))

function greet() {
  var reply = [this.person, 'Is An Awesome', this.role].join(' ');
  console.log(reply);
}

var i = {
  person: 'Douglas Crockford', role: 'Javascript Developer'
};

greet.call(i); // Douglas Crockford Is An Awesome Javascript Developer

這幾個例子 歸根結(jié)底都是為了指定在函數(shù)被調(diào)用時執(zhí)行上下文中 this 的指向。

apply() 的使用場景和例子

參數(shù)數(shù)量不明確時只能用 apply(),然后把參數(shù) push 進數(shù)組傳遞進去。當然 函數(shù)內(nèi)部也可以通過 arguments 這個類數(shù)組對象來遍歷所有的參數(shù)。

1.redux 的 bindActionCreators()中的bindActionCreator()定義如下

//ES6 寫法
function bindActionCreator(actionCreator, dispatch) {
  return (...args) => dispatch(actionCreator(...args))
}
//被bable 轉(zhuǎn)譯到ES5后
function bindActionCreator(actionCreator, dispatch) {
  return function () {
    return dispatch(actionCreator.apply(undefined, arguments));
  };
}

因為被返回的函數(shù)調(diào)用時傳入的參數(shù)個數(shù)不確定,所以這里只能用apply().
要注意該例中的arguments 是類數(shù)組對象。并不是數(shù)組(并不是Array 的實例)

對數(shù)組或類數(shù)組對象, 用apply()調(diào)用參數(shù)列表與之相對應(yīng)的已存在函數(shù)。

1.數(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] */

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

var numbers = [5, 6, 2, 3, 7]
var max = Math.max.apply(null, numbers); 
var min = Math.min.apply(null, numbers);

/*若不用apply() 就要做復(fù)雜的數(shù)組遍歷*/
max = -Infinity, min = +Infinity;
for (var i = 0; i < numbers.length; i++) {
  if (numbers[i] > max)
    max = numbers[i];
  if (numbers[i] < min) 
    min = numbers[i];
}

/*ES6中也可以使用數(shù)組擴展運算符配合call()代替,但還是略麻煩*/
var max = Math.max.call(null, ...numbers); 

再談bind()

bind()方法會創(chuàng)建一個新函數(shù),稱為綁定函數(shù),當調(diào)用這個綁定函數(shù)時,綁定函數(shù)會以創(chuàng)建它時傳入 bind()方法的第一個參數(shù)作為 this,傳入 bind() 方法的第二個以及以后的參數(shù)加上綁定函數(shù)運行時本身的參數(shù)按照順序作為原函數(shù)的參數(shù)來調(diào)用原函數(shù)。

bind 和與其他兩者有個重要區(qū)別: bind 是在函數(shù)定義階段指定函數(shù)執(zhí)行上下文的this指向,綁定之后不會立即去調(diào)用。

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

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

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