开发者

Convention for namespacing classes vs instances in javascript?

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()

an开发者_StackOverflowd 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜