我习惯使用以下语法,我相信它被广泛使用:
var foo = foo || {};
(function() {
foo.bar = function(){
return this;
};
foo.bar.prototype.stuff = null;
foo.bar.prototype.do = function(){...};
})();
这可以使用闭包实现,也可以不使用。
我使用foo.bar.prototype.stuff语法,以避免将所有定义放在构造函数中。
在ECS6中,我尝试了这种语法:
class Foo{};
class Bar{
constructor(){
this.stuff = null;
}
get moreStuff(){ return this.stuff++;}
do(){...}
}
Foo.Bar = Bar;
module.exports = { Foo };
我发现在使用这种语法时,Intellisense在Visual Studio Code中非常方便。
有人看到这种语法有什么问题吗?如果有,请修改并提出更好的建议。
我阅读了这篇文章《如何在JavaScript中声明命名空间?》,发现许多提议的语法都是在ECS6之前提出的。
Bar
分配到Foo
上呢?你可以将它们都放在exports
中,并从那里访问它们。 - loganfsmythmodule.exports = Bar;
即可。如果你需要这个类,可以使用文件路径来进行require()
。 - loganfsmyth