最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

js bind 函數 使用閉包保存執(zhí)行上下文

 更新時間:2011年12月26日 23:17:33   作者:  
在javascript中,函數總是在一個特殊的上下文執(zhí)行(稱為執(zhí)行上下文),如果你將一個對象的函數賦值給另外一個變量的話,這個函數的執(zhí)行上下文就變?yōu)檫@個變量的上下文了。下面的一個例子能很好的說明這個問題
復制代碼 代碼如下:

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"

如果你希望將一個對象的函數賦值給另外一個變量后,這個函數的執(zhí)行上下文仍然為這個對象,那么就需要用到bind方法。
bind的實現(xiàn)如下:
復制代碼 代碼如下:

// 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)));
};
};

使用示例:
復制代碼 代碼如下:

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文檔解釋的這么詳細,一定要花點時間多看看了。
我的簡單的實現(xiàn):
復制代碼 代碼如下:

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());

相關文章

最新評論

门源| 九龙县| 池州市| 湖口县| 界首市| 邳州市| 葵青区| 从化市| 苏尼特左旗| 武安市| 巴东县| 临夏市| 池州市| 宾阳县| 黎城县| 平顶山市| 涿鹿县| 临湘市| 靖远县| 巴青县| 历史| 蒙城县| 上饶县| 昭苏县| 论坛| 巢湖市| 禹城市| 大渡口区| 东乌珠穆沁旗| 封开县| 师宗县| 富平县| 宜兰县| 军事| 辽阳县| 南皮县| 科尔| 永登县| 文昌市| 治县。| 武城县|