手机
当前位置:查字典教程网 >编程开发 >Javascript教程 >js bind 函数 使用闭包保存执行上下文
js bind 函数 使用闭包保存执行上下文
摘要:复制代码代码如下:window.name="thewindowobject"functionscopeTest(){returnthis.n...

复制代码 代码如下:

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文档解释的这么详细,一定要花点时间多看看了。

我的简单的实现:

复制代码 代码如下:

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 bind 函数 使用闭包保存执行上下文】相关文章:

Javascript调用XML制作连动下拉列表框

JavaScript调试技巧

浅析Javascript匿名函数与自执行函数

用javascript制作放大镜放大图片

javascript用函数实现对象的方法

js控制网页前进和后退的方法

简介JavaScript中Math.LOG10E属性的使用

JavaScript函数使用的基本教程

javascript中FOREACH数组方法使用示例

jquery 构造函数在表单提交过程中修改数据

精品推荐
分类导航