javascript中的bind

[url]http://www.prototypejs.org/api/function/bind[/url]

In JavaScript, functions are executed in a specific context (often referred to as “scope”). [b]Inside the function the[/b] [i]this[/i] [b]keyword becomes a reference to that scope[/b]. Since every function is in fact a property of some object—global functions are properties of the window object—the execution scope is the object from which the function was called, or (more precisely) the object that holds a reference to the function:


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!"

Because of the dynamic nature of the language, we can’t be sure that, for instance, otherScopeTest() will always be called on our foo object. The reference to it can be copied somewhere else, like on the window object:


// ... continuing from the last example

// note that we aren't calling the function, we're simply referencing it
window.test = foo.otherScopeTest
// now we are actually calling it:
test()
// -> "the window object"

The last call demonstrates how the same function can behave differently depending on its execution scope.

When you begin passing around function references in your code, you often want them to become fixated on a specific scope. Prototype can guarantee that your function will execute with the object you want under the this keyword just by invoking bind on it. You can also save the returned function and use it multiple times if you need so.

Examples
The code below is simply proof-of-concept:


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);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值