js bind 函數(shù) 使用閉包保存執(zhí)行上下文
更新時(shí)間:2011年12月26日 23:17:33 作者:
在javascript中,函數(shù)總是在一個(gè)特殊的上下文執(zhí)行(稱為執(zhí)行上下文),如果你將一個(gè)對(duì)象的函數(shù)賦值給另外一個(gè)變量的話,這個(gè)函數(shù)的執(zhí)行上下文就變?yōu)檫@個(gè)變量的上下文了。下面的一個(gè)例子能很好的說(shuō)明這個(gè)問(wèn)題
復(fù)制代碼 代碼如下:
window.name = "the window object"
function scopeTest() {
return this.name;
}
// calling the function in global scope:
scopeTest()
// -> "the window object"
var foo = {
name: "the foo object!",
otherScopeTest: function() { return this.name }
};
foo.otherScopeTest();// -> "the foo object!"
var foo_otherScopeTest = foo.otherScopeTest;
foo_otherScopeTest();
// –> "the window object"
如果你希望將一個(gè)對(duì)象的函數(shù)賦值給另外一個(gè)變量后,這個(gè)函數(shù)的執(zhí)行上下文仍然為這個(gè)對(duì)象,那么就需要用到bind方法。
bind的實(shí)現(xiàn)如下:
復(fù)制代碼 代碼如下:
// The .bind method from Prototype.js
Function.prototype.bind = function(){
var fn = this, args = Array.prototype.slice.call(arguments), object = args.shift();
return function(){
return fn.apply(object,
args.concat(Array.prototype.slice.call(arguments)));
};
};
使用示例:
復(fù)制代碼 代碼如下:
var obj = {
name: 'A nice demo',
fx: function() {
alert(this.name);
}
};
window.name = 'I am such a beautiful window!';
function runFx(f) {
f();
}
var fx2 = obj.fx.bind(obj);
runFx(obj.fx);
runFx(fx2);
參考:
http://www.prototypejs.org/api/function/bind
PS:
才發(fā)現(xiàn)prototypejs的API文檔解釋的這么詳細(xì),一定要花點(diǎn)時(shí)間多看看了。
我的簡(jiǎn)單的實(shí)現(xiàn):
復(fù)制代碼 代碼如下:
Function.prototype.bind = function(obj) {
var _this = this;
return function() {
return _this.apply(obj,
Array.prototype.slice.call(arguments));
}
}
var name = 'window',
foo = {
name:'foo object',
show:function() {
return this.name;
}
};
console.assert(foo.show()=='foo object',
'expected foo object,actual is '+foo.show());
var foo_show = foo.show;
console.assert(foo_show()=='window',
'expected is window,actual is '+foo_show());
var foo_show_bind = foo.show.bind(foo);
console.assert(foo_show_bind()=='foo object',
'expected is foo object,actual is '+foo_show_bind());
您可能感興趣的文章:
- JS ES6中setTimeout函數(shù)的執(zhí)行上下文示例
- 深入理解JavaScript 中的執(zhí)行上下文和執(zhí)行棧
- 一篇文章弄懂javascript中的執(zhí)行棧與執(zhí)行上下文
- JavaScript ECMA-262-3 深入解析(一):執(zhí)行上下文實(shí)例分析
- 通過(guò)實(shí)例了解JS執(zhí)行上下文運(yùn)行原理
- Javascript執(zhí)行上下文順序的深入講解
- js 執(zhí)行上下文和作用域的相關(guān)總結(jié)
- 詳解JavaScript中的執(zhí)行上下文及調(diào)用堆棧
- 深入學(xué)習(xí)JavaScript執(zhí)行上下文
相關(guān)文章
前端無(wú)感知刷新token以及超時(shí)自動(dòng)退出實(shí)現(xiàn)方案
前端需要做到無(wú)感刷新token,即刷token時(shí)要做到用戶無(wú)感知,避免頻繁登錄,下面這篇文章主要給大家介紹了關(guān)于前端無(wú)感知刷新token以及超時(shí)自動(dòng)退出的實(shí)現(xiàn)方案,需要的朋友可以參考下2024-01-01
JS獲取指定時(shí)間的時(shí)間戳的方法匯總(最新整理收藏版)
在JavaScript中,可以使用Date.parse()或new Date()來(lái)獲取指定時(shí)間的時(shí)間戳,本文給大家分享JS獲取指定時(shí)間的時(shí)間戳的方法,感興趣的朋友一起看看吧2024-01-01
jsonp跨域及實(shí)現(xiàn)百度首頁(yè)聯(lián)想功能的方法
這篇文章主要介紹了jsonp跨域及實(shí)現(xiàn)百度首頁(yè)聯(lián)想功能的方法,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-08-08

