说下js中的bind
生活随笔
收集整理的這篇文章主要介紹了
说下js中的bind
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
bind的受體是對象,返回的是個新的函數。
我們知道this總是指向調用他的對象。但是有時候我們希望‘固化’這個this。
也就是無論怎么調用這個返回的函數都有同樣的this值。
這就是bind的作用。
語法
fun.bind(thisArg[, arg1[, arg2[, ...]]])
參數
thisArg
當綁定函數被調用時,該參數會作為原函數運行時的 this 指向。當使用new操作符調用綁定函數時,該參數無效。
this將永久地被綁定到了bind的第一個參數,無論這個函數是如何被調用的。
arg1, arg2, ...
當綁定函數被調用時,這些參數將置于實參之前傳遞給被綁定的方法。
返回值
返回由指定的this值和初始化參數改造的原函數拷貝
例1
window.color = 'red'; var o = {color: 'blue'};function sayColor(){alert(this.color); } var func = sayColor.bind(o); // 輸出 "blue", 因為傳的是對象 o,this 始終指向 o func();var func2 = sayColor.bind(this); // 輸出 "red", 因為傳的是this,在全局作用域中this代表 window。等于傳的是 window。 func2();例2
注意:bind只生效一次
function f(){return this.a; }//this被固定到了傳入的對象上 var g = f.bind({a:"azerty"}); console.log(g()); // azertyvar h = g.bind({a:'yoo'}); //bind只生效一次! console.log(h()); // azertyvar o = {a:37, f:f, g:g, h:h}; console.log(o.f(), o.g(), o.h()); // 37, azerty, azerty例3
var myObj = {specialFunction: function () {},anotherSpecialFunction: function () {},getAsyncData: function (cb) {cb();},render: function () {// 注意這里,寫成 this.specialFunction() 會報錯var that = this;this.getAsyncData(function () {that.specialFunction();that.anotherSpecialFunction();});} };myObj.render();// 使用 bind 優化 // 當myObj 調用,this就指向了myObj render: function () {this.getAsyncData(function () {this.specialFunction();this.anotherSpecialFunction();}.bind(this)); }例4
使用bind可少寫匿名函數
<button>Clict Me!</button> <script> var logger = {x: 0,updateCount: function(){this.x++;console.log(this.x);} }// document.querySelector('button').addEventListener('click', function(){ // logger.updateCount(); // }); // 優化后 // 因為bind返回就是新的函數,不用再寫匿名函數了。 document.querySelector('button').addEventListener('click', logger.updateCount.bind(logger))參考
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
https://www.smashingmagazine.com/2014/01/understanding-javascript-function-prototype-bind/#what-problem-are-we-actually-looking-to-solve
總結
以上是生活随笔為你收集整理的说下js中的bind的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql 5.7 学习
- 下一篇: 高并发下的static类成员可能存在安全