日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

说下js中的bind

發布時間:2025/3/19 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 说下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的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。