在JavaScript中命名空间类与实例的约定? [英] Convention for namespacing classes vs instances in javascript?

查看:122
本文介绍了在JavaScript中命名空间类与实例的约定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下代码创建一个类的实例:

  test = new function(){
...
}

但是,base没有原型,匿名函数(我猜这是原因?)。这使我无法为实例创建任何公共函数。



你可以说我可以通过简单的做:

  function testClass(){
...
}
test = new testClass()

,然后将公共函数附加到testClass。
但是这迫使我做不必要的命名空间。特别是,如果我命名我的类this.is.a.space,那么我该调用我的实例? this.is.a.spaceInstance?

解决方案

您仍然可以编写匿名函数,并使用 .__ proto __ 来访问它的原型:

  test = new function(){
...
};

test.__proto__.foo = function(){return 1};但是,你只有一个实例,所以你也可以只使用:


  test.foo = function(){return 1}; 

我不完全确定你想要完成什么,通常按照 someVariable 的行来命名类 SomeClass 和其他变量(类似实例)。 JavaScript区分大小写,因此您可以使用 TestClass / testClass


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?

解决方案

You can still code the anonymous function and use .__proto__ to access its prototype like this:

test = new function(){
    ...
};

test.__proto__.foo = function() { return 1 };

However, you only have one instance so you could also just use:

test.foo = function() { return 1 };

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 of someVariable. JavaScript is case-sensitive so you could use TestClass/testClass.

这篇关于在JavaScript中命名空间类与实例的约定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆