【发布时间】:2011-06-16 22:59:46
【问题描述】:
我刚接触 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: 使用上面的代码 sn-p 我发现了一个奇怪的命名空间污染副作用,如下 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 上测试的,我不知道 SomeObject 是如何让 SomeFunc 成为成员的。这似乎是我有限的原型知识中的一个漏洞。谁能解释一下?
【问题讨论】:
标签: javascript prototype namespaces