我刚开始在为Javascript,所以我在命名空间中的第一次尝试最终看上去像这样:的Javascript命名空间污染问题
var myNameSpace = {};
var myNameSpaceProto = myNameSpace.__proto__;
myNameSpaceProto.SomeFunc = function()
{
alert("SomeFunc()");
};
myNameSpaceProto.SomeObject = function()
{
alert("SomeObject constructor");
};
var instance = new myNameSpace.SomeObject();
我收集我可以跳过原型步骤,只需有myNameSpace.SomeFunc = function...
,因为只有一个myNameSpace
对象实例,所以原型不保存任何东西。
问题1:这是正确的吗?我想从几个独立的.js文件添加到命名空间,所以这种方式看起来很方便。
问题2:与上面的代码段,我发现的命名空间的污染,这是由以下SomeObject
体所示的奇怪的副作用:
myNameSpaceProto.SomeObject = function()
{
// As expected NonexistantFunc is not a member of this and returns "undefined"
alert("typeof this.NonexistantFunc = " + typeof this.NonexistantFunc);
// Returns 'function'. How has SomeFunc made it to this.SomeFunc? It's supposed to be under myNameSpace.SomeFunc
alert("typeof this.SomeFunc = " + typeof this.SomeFunc);
// Turns out it's in the prototype's prototype. Why?
alert("this.__proto__.__proto__.SomeFunc = " + this.__proto__.__proto__.SomeFunc);
};
这是在Chrome 8和I可以测试不知道如何SomeObject
已成为SomeFunc
成员。这似乎是我对原型有限知识的一个漏洞。有人可以解释吗?
谢谢,很好的答案:)我来自C++背景,人们说* *语言有陷阱... – AshleysBrain 2011-01-28 17:29:15