got*_*ch4 6 javascript closures
我在Javascript中使用这个片段,每天100次,以封闭对象:
Class.prototype.Method = function(arg){
var Ta = this;
var e = function(){
Ta.doSomething(arg);
};
};
Run Code Online (Sandbox Code Playgroud)
有没有办法避免Ta变量,仍然参考"外部"(这个词是否正确?)对象?
a) 您可以继续使用此方法并使用更有意义的变量名称。使用that是一个常见的约定——它表明你的变量只是另一个“this”值,但用于另一个函数范围。
b) 您可以使用函数绑定实用程序。一些 JavaScript 库附带了一个。或者你可以简单地自己推出:
function bind(fn, scope) {
return function () {
fn.apply(scope, arguments);
};
}
// for your example:
Class.prototype.Method = function(arg) {
var e = bind(function() {
this.doSomething(arg);
}, this);
};
// Alternatively, extend the Function prototype (may raise some eyebrows):
Function.prototype.bind = function (scope) {
var fn = this;
return function () {
fn.apply(scope, arguments);
};
};
// for your example:
Class.prototype.Method = function(arg) {
var e = function() {
this.doSomething(arg);
}.bind(this);
};
Run Code Online (Sandbox Code Playgroud)
更新:
正如 @Pointy 所指出的,bind它实际上是 JavaScript 规范新版本的一部分,已经被现代浏览器采用:https ://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind
| 归档时间: |
|
| 查看次数: |
280 次 |
| 最近记录: |