Luc*_*zzi 7 javascript singleton this
我有类似的东西:
var a = (function () {
return {
b: 1,
c: function () {
console.log(this.b);
}
};
})();
Run Code Online (Sandbox Code Playgroud)
所以,
a.c(); // = 1
Run Code Online (Sandbox Code Playgroud)
但如果我这样做
b = 2;
a.c.apply(this); // = 2
Run Code Online (Sandbox Code Playgroud)
是否有可能在"ac()"中保留"this"的上下文而不改变(太多)"a"对象的结构?我没有对函数调用的控制,所以我需要一个解决方法来处理对象本身内部的这个问题.
更新:
更具体地说,这是我的文件的结构:
结构1(单身模式):
var a = (function () {
var _instance;
function init() {
return {
b: 1,
c: function () {
console.log(this.b);
}
};
}
return {
getInstance: function () {
if (_instance === undefined) {
_instance = init();
}
return _instance;
}
}
})();
Run Code Online (Sandbox Code Playgroud)
结构2:
var b = {
c: 1,
d: function () {
console.log(this.c);
}
};
Run Code Online (Sandbox Code Playgroud)
解决方案:
我已经实现了一个基于Mahout的答案的解决方案,将return语句拆分为init(),因此在任何情况下它都可以安全地保存对象上下文(和实例).
对于单身人士模式:
var a = (function () {
var _instance,
self;
function init() {
return self = {
b: 1,
c: function () {
console.log(self.b);
}
};
}
return {
getInstance: function () {
if (_instance === undefined) {
_instance = init();
}
return _instance;
}
};
})();
Run Code Online (Sandbox Code Playgroud)
对于对象文字:
var b = (function () {
var self;
return self = {
c: 1,
d: function () {
console.log(self.c);
}
};
})();
Run Code Online (Sandbox Code Playgroud)
所以
a.getInstance().c(); // 1
a.getInstance().c.apply(this); // 1
setTimeout(a.getInstance().c, 1); // 1
$.ajax({ complete: a.getInstance().c }); // 1
Run Code Online (Sandbox Code Playgroud)
您可以稍微更改从匿名函数返回对象的方式:
var a = (function () {
var result = {};
result.b = 2;
result.c = function() {
console.log(result.b);
};
return result;
})();
Run Code Online (Sandbox Code Playgroud)
这应该具有相同的效果,但是它确实消除了this.
如果你无力改变a这么多的结构,那么你可以(更)更危险地使用:
a.c.apply = function() { // Stops the apply function working on a.c by overriding it
return a.c();
}
Run Code Online (Sandbox Code Playgroud)
如果您选择此选项,则必须小心,任何时候a.c.apply使用它都将不再“按预期”工作 - 但它会解决此处提出的问题。
| 归档时间: |
|
| 查看次数: |
452 次 |
| 最近记录: |