javascript 中命名空间类与实例的约定?
我正在使用以下代码创建一个类的实例:
test = new function(){
...
}
但是,base 没有原型,因为它是从匿名函数创建的(我猜这就是原因?)。这使我无法为该实例创建任何公共函数。
你可能会说我可以通过简单地执行以下操作来解决这个问题:
function testClass(){
...
}
test = new testClass()
然后将公共函数附加到 testClass。 但这迫使我进行不必要的命名空间。特别是,如果我将我的类命名为 this.is.a.space,那么我将如何称呼我的实例?这是一个空间实例吗?这是一个空间实例吗?
对于此类事情有约定吗?
I am creating a instance of a class using the following code:
test = new function(){
...
}
However, base has no prototype because it was created from an anonymous function (I'm guessing this is the reason?). This leaves me unable to create any public functions for the instance.
You could argue I could get around this by simply doing:
function testClass(){
...
}
test = new testClass()
and then attaching public functions to testClass.
But this forces me to do unnecessary namespacing. In particular, if I were to name my class this.is.a.space, then what would I call my instance? this.is.a.spaceInstance? this.is.a.space.Instance?
Is there a convention for this sort of thing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您仍然可以编写匿名函数并使用
.__proto__
访问其原型,如下所示:但是,您只有一个实例,因此您也可以使用:
我不完全确定您到底是什么尝试完成,但至于命名,通常将类命名为
SomeClass
,其他变量(如实例)则命名为someVariable
。 JavaScript 区分大小写,因此您可以使用TestClass
/testClass
。You can still code the anonymous function and use
.__proto__
to access its prototype like this:However, you only have one instance so you could also just use:
I'm not completely sure what exactly you're trying to accomplish, but as for the naming, it is usual to name the class like
SomeClass
and other variables (like instances) along the lines ofsomeVariable
. JavaScript is case-sensitive so you could useTestClass
/testClass
.