我如何确定这个“公共”范围?方法正确吗?
我有这段代码 (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();
这是我遇到的实际问题的抽象。
所以 - 我希望对 OBJ.thePrivateVarTimeout() 的调用等待 10 ,然后用 23 进行警报(我希望它通过其他暴露的方法)。
但是 self
似乎设置不正确。当我设置 self = this 时,this 似乎不是对函数的引用,而是对全局对象的引用。这是为什么呢?
如何使公共方法 thePrivateVarTimeout
调用另一个公共方法 thePrivateVar
?
I have this code (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();
This is an abstraction of a real problem I'm having.
So - I would expect the call to OBJ.thePrivateVarTimeout()
to wait 10
and then alert
with 23 (which I want it to access through the other exposed method).
However self
doesn't seem to be setting correctly. When I am setting self = this
it appears that this
isn't a reference to the function but a reference to the global object. Why is this?
How can I make the public method thePrivateVarTimeout
call the other public method thePrivateVar
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
this === 全局 ||被调用函数内未定义。在 ES5 中,无论全局环境是什么,在严格的 ES5 中,它都是未定义的。
更常见的模式涉及使用
var that = this
作为函数中的本地值或使用
.bindAll
方法this === global || undefined
inside an invoked function. In ES5 it's whatever the global environment is, in ES5 strict it is undefined.More common patterns would involve using the
var that = this
as a local value in a functionor using a
.bindAll
method