无为清净楼资源网 Design By www.qnjia.com
复制代码 代码如下:
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());
标签:
bind,闭包保存

无为清净楼资源网 Design By www.qnjia.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
无为清净楼资源网 Design By www.qnjia.com

RTX 5090要首发 性能要翻倍!三星展示GDDR7显存

三星在GTC上展示了专为下一代游戏GPU设计的GDDR7内存。

首次推出的GDDR7内存模块密度为16GB,每个模块容量为2GB。其速度预设为32 Gbps(PAM3),但也可以降至28 Gbps,以提高产量和初始阶段的整体性能和成本效益。

据三星表示,GDDR7内存的能效将提高20%,同时工作电压仅为1.1V,低于标准的1.2V。通过采用更新的封装材料和优化的电路设计,使得在高速运行时的发热量降低,GDDR7的热阻比GDDR6降低了70%。