JavaScript bind方法

MDN一句話介紹bind:

bing() 方法會創(chuàng)建一個新函數(shù)。當(dāng)這個新函數(shù)被調(diào)用時,bind()的第一個參數(shù)將作為它運行時的this, 之后的一序列參數(shù)將會在傳遞的實參前傳入它的參數(shù)。

由此我們可以得出bind函數(shù)的兩個特點:

  1. 返回一個函數(shù)
  2. 可以傳入?yún)?shù)
var foo = {
  value: 1
};
function bar(name, age) {
  console.log(this.value);
  console.log(name);
  console.log(age);
}
bar(); // undefiend undefiend undefiend
var barBind = bar.bind(foo);
barBind(); // 1 undefiend undefiend
barBind('jump', 18);// 1 jump 18

bind 特點

一個綁定函數(shù)也能使用new操作符創(chuàng)建對象:這種行為就像把原函數(shù)當(dāng)成構(gòu)造器。提供的this值被忽略。

也就是說當(dāng)bind返回的函數(shù)作為構(gòu)造函數(shù)的時候, bind時指定的this值會失效,但是參數(shù)仍然生效。

var value = 2;
var foo = {
  value: 3
};
var bar = function(name,age) {
  console.log(this.value);
  console.log(name);
  console.log(age);
}
var barBind = bar.bind(foo,'jump',18);
var bindObj = new barBind();
console.log(bindObj);// undefiend jump 18
  • 注意: 盡管在全局和foo中都聲明了value值, 最后依然返回了undefiend, 說明綁定的this失效了, 因為這個時候的this已經(jīng)指向了bindObj。
最后編輯于
?著作權(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)容