从我的命名空间内访问我的公共方法
我正在 JavaScript 中创建自己的命名空间...
(function(window){
(function(){
var myNamespace = {
somePublicMethod: function(){
},
anotherPublicMethod: function(){
}
}
return (window.myNamespace = window.my = myNamespace)
}());
})(window);
我对这些高级 JavaScript 技术很陌生,我正在尝试找出从我的命名空间中调用公共方法的最佳方法。看来在我的公共方法中 this
被设置为 myNamespace
。
我应该调用公共方法,例如...
AnotherPublicMethod: function(){
this.somePublicMethod()
}
或...
AnotherPublicMethod: function(){
my.somePublicMethod();
}
有什么区别吗?
I am in the process of making my own namespace in JavaScript...
(function(window){
(function(){
var myNamespace = {
somePublicMethod: function(){
},
anotherPublicMethod: function(){
}
}
return (window.myNamespace = window.my = myNamespace)
}());
})(window);
I'm new to these kinds of advanced JavaScript techniques and i'm trying to figure out the best way to call public methods from within my namespace. It appears that within my public methods this
is being set to myNamespace
.
Should I call public methods like...
AnotherPublicMethod: function(){
this.somePublicMethod()
}
or...
AnotherPublicMethod: function(){
my.somePublicMethod();
}
is there any difference?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在我看来,如果您使用
this
,您将使用对该对象的直接引用,而如果您使用my
,解释器将需要遍历作用域链直到它找到my
作为window
的属性。但反过来也可能存在争论。
编辑:
我应该注意,由于
this
是由函数的调用方式决定的,因此它要求 Activation 对象是该对象。所以这可行:
但这不行:
如果有可能,那么您应该使用
my
或对该对象的其他直接引用。您可以通过维护对对象的引用来减少作用域链遍历。您的myNamespace
变量应该可以工作。有点偏离主题,但我还注意到您的代码将无法按原样运行。
此行:
...无权访问
myNamespace
变量。也许你的意思更像是这样?
The way I see it, if you use
this
you're using a direct reference to the object, whereas if you usemy
, the interpreter would need to traverse the scope chain until it findsmy
as a property ofwindow
.But there may be arguments the other way as well.
EDIT:
I should note that since
this
is determined by how the function is called, it would require that the Activation object be that object.So this would work:
But this would not:
If that's a possibility, then you should use
my
, or some other direct reference to the object. You could reduce the scope chain traversal by maintaining a reference to the object. YourmyNamespace
variable should work.A little off topic, but I'd also note that your code won't work the way it is.
This line:
...doesn't have access to the
myNamespace
variable.Perhaps you meant something more like this?