Convention for namespacing classes vs instances in javascript?

十年热恋 提交于 2019-12-10 11:39:19

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/6439031/convention-for-namespacing-classes-vs-instances-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!