在 javascript 中,函数总是在一个特殊的上下文执行(称为执行上下文),如果你将一个对象的函数赋值给另外一个变量的话,这个函数的执行上下文就变为这个变量的上下文了。下面的一个例子能很好的说明这个问题
Javascript 是一种由 Netscape 的 LiveScript 发展而来的原型化继承的基于对象的动态类型的区分大小写的客户端脚本语言,主要目的是为了解决服务器端语言,比如 Perl,遗留的速度问题,为客户提供更流畅的浏览效果。
- 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"
如果你希望将一个对象的函数赋值给另外一个变量后,这个函数的执行上下文仍然为这个对象,那么就需要用到 bind 方法。
bind 的实现如下:
- // 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: 才发现 prototypejs 的 API 文档解释的这么详细,一定要花点时间多看看了。 我的简单的实现:
来源: