Convention for namespacing classes vs instances in

2019-05-31 05:39发布

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条回答
走好不送
2楼-- · 2019-05-31 05:49

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.

查看更多
登录 后发表回答