El *_*oco 5 javascript scope public-members
我有这个代码(JSFiddle)
var OBJ = function(){
var privateVar = 23;
var self = this;
return {
thePrivateVar : function() {
return privateVar;
},
thePrivateVarTimeout : function() {
setTimeout(function() { alert(self.thePrivateVar()); } , 10);
}
}
}();
alert(OBJ.thePrivateVar());
OBJ.thePrivateVarTimeout();
Run Code Online (Sandbox Code Playgroud)
这是我正在遇到的一个真正问题的抽象.
所以 - 我希望调用OBJ.thePrivateVarTimeout()等待10然后alert使用23(我希望它通过其他公开的方法访问).
但self似乎没有正确设置.当我设置self = this它时,它似乎this不是对函数的引用,而是对全局对象的引用.为什么是这样?
如何让public方法thePrivateVarTimeout调用其他公共方法thePrivateVar?
var OBJ = (function(){
var privateVar = 23;
var self = {
thePrivateVar : function() {
return privateVar;
},
thePrivateVarTimeout : function() {
setTimeout(function() { alert(self.thePrivateVar); } , 10);
}
};
return self;
}());
Run Code Online (Sandbox Code Playgroud)
this === global || undefined在一个被调用的函数里面.在ES5中,无论全局环境如何,在ES5严格中它都是未定义的.
更常见的模式将涉及var that = this在函数中使用作为局部值
var obj = (function() {
var obj = {
property: "foobar",
timeout: function _timeout() {
var that = this;
setTimeout(alertData, 10);
function alertData() {
alert(that.property);
}
}
}
return obj;
}());
Run Code Online (Sandbox Code Playgroud)
或使用.bindAll方法
var obj = (function() {
var obj = {
alertData: function _alertData() {
alert(this.property);
}
property: "foobar",
timeout: function _timeout() {
setTimeout(this.alertData, 10);
}
}
bindAll(obj)
return obj;
}());
/*
bindAll binds all methods to have their context set to the object
@param Object obj - the object to bind methods on
@param Array methods - optional whitelist of methods to bind
@return Object - the bound object
*/
function bindAll(obj, whitelist) {
var keys = Object.keys(obj).filter(stripNonMethods);
(whitelist || keys).forEach(bindMethod);
function stripNonMethods(name) {
return typeof obj[name] === "function";
}
function bindMethod(name) {
obj[name] = obj[name].bind(obj);
}
return obj;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
92 次 |
| 最近记录: |