您的位置:首页 > Web前端 > JavaScript

Js bind 函数 使用闭包保存执行上下文

2013-08-22 18:26 405 查看
转载:http://www.codesky.net/article/201208/170849.html

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"

var foo_otherScopeTest = foo.otherScopeTest.bind(foo);; 
foo_otherScopeTest(); 
// "the
foo object!"

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))); 
}; 
}; 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: