首頁 > web前端 > js教程 > 主體

深入理解JS中的Function.prototype.bind()方法

高洛峰
發布: 2017-01-04 10:02:56
原創
1123 人瀏覽過

前言

對於函數綁定(Function binding)很有可能是大家在使用JavaScript時最少關注的一點,但是當你意識到你需要一個解決方案來解決如何在另一個函數中保持this上下文的時候,你真正需要的其實就是 Function.prototype.bind() ,只是你有可能還是沒有意識到這一點。

第一次遇到這個問題的時候,你可能傾向於將this設定到一個變數上,這樣你可以在改變了上下文之後繼續引用它。

一. bind的語法

bind() 方法的主要作用就是將函數綁定至某個對象,bind() 方法會創建一個函數,函數體內this對象的值會被綁定到傳入bind () 函數的值。

1.1 定義

bind()的定義如下:

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a new function is called.

bind() 函數會建立一個新函數(稱為綁定函數),新函數與被調函數(綁定函數的目標函數)具有相同的函數體。當目標函數被呼叫時 this 值綁定到 bind() 的第一個參數,則該參數不能被重寫。

1.2 原理

可以用以下程式碼模擬bind()的原理:

Function.prototype.bind = function(context) {
 var self = this; // 保存原函数
 return function() { // 返回一个新函数
  return self.apply(context, arguments); // 执行新函数时,将传入的上下文context作为新函数的this
 }
}
登入後複製

1.3 語法

Function.prototype.bind(thisArg[, arg1[, arg2[, ...]]])
登入後複製

二. bind的應用場景

2.1 實現物件繼承時間

var A = function(name) {
 this.name = name;
}
 
var B = function() {
 A.bind(this, arguments);
}
 
B.prototype.getName = function() {
 return this.name;
}
 
var b = new B("hello");
console.log(b.getName()); // "hello"
登入後複製

2.4 借用Array的原生方法

var paint = {
 color: "red",
 count: 0,
 updateCount: function() {
  this.count++;
  console.log(this.count);
 }
};
 
// 事件处理函数绑定的错误方法:
document.querySelector('button')
 .addEventListener('click', paint.updateCount); // paint.updateCount函数的this指向变成了该DOM对象
 
// 事件处理函数绑定的正确方法:
document.querySelector('button')
 .addEventListener('click', paint.updateCount.bind(paint)); // paint.updateCount函数的this指向变成了paint
登入後複製

三. bind()方法的瀏覽器相容性

四. bind()的相容性寫法

var notify = {
 text: "Hello World!",
 beforeRender: function() {
  alert(this.text);
 },
 render: function() {
 
  // 错误方法:
  setTimeout(this.beforeRender, 0); // undefined
 
  // 正确方法:
  setTimeout(this.beforeRender.bind(this), 0); // "Hello World!"
 }
};
 
notify.render();
登入後複製
深入理解JS中的Function.prototype.bind()方法 apply方法的區別

共同點:

都可以改變函數執行的上下文環境;

不同點:

bind: 不立即執行函數,一般用在非同步呼叫和事件; call/apply: 立即執行函數。

總結

好了,以上就是這篇文章的全部內容了,希望本文的內容對大家學習或使用Javascript能有一定的幫助,如果有疑問大家可以留言交流。

更多X深入理解JS中的Function.prototype.bind()方法相關文章請關注PHP中文網!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!