Javascript 文字对象内的私有 var
如何在文字对象中声明私有变量?因为我有这段代码:
var foo = {
self: null,
init: function() {
self = this;
self.doStuff();
},
doStuff: function() {
//stuff here
}
}
这工作得很好,但是如果我有一些对象,它会覆盖 var“self”..显然它是一个全局变量..并且我不能在这个对象内使用受限制的单词“var”..
我该如何解决这个问题,或者为每个对象创建一个命名空间?
谢谢!
How can I declare a private var inside a literal object? Becasuse I've this code:
var foo = {
self: null,
init: function() {
self = this;
self.doStuff();
},
doStuff: function() {
//stuff here
}
}
This works perfectly, but if I have some objects, the var "self" it will override.. apparently it's a global var.. and I cannot use the restricted word "var" inside this object..
How can I solve this, or make an NameSpace for each object?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以创建一个函数作用域来隐藏变量:
尽管不清楚
self
在这里应该做什么,以及如何使用foo
。You can create a function scope to hide the variable:
Though it is not clear what
self
is supposed to do here, and howfoo
is used.您必须使用
this
:edit 但是,它仍然是“foo”对象的属性,并且您在哪里获取“foo”实例并不是非常清楚从。换句话说,按照代码的编写方式,只有一个对象。
或者,您可以使用闭包创建对象:
You have to use
this
:edit However, it's still a property of the "foo" object, and it's not super-clear where you're getting instances of "foo" from. In other words, the way your code is written, there's only one object.
Alternatively, you could create your object with a closure:
您甚至没有使用您创建的财产。相反,您创建另一个具有相同名称的全局变量。使用
this
关键字访问属性:(尽管将
this
保存在属性中确实毫无意义...)如果您想在对象中使用局部变量,请为它创建一个闭包它:
You are not even using the property that you have created. Instead you create another global variable with the same name. Use the
this
keyword to access properties:(Although saving
this
in a property is truly pointless...)If you want a local variable in the object, create a closure for it: