Brian Brian - 5 months ago 17
Javascript Question

What happens in JavaScript when defining objects on Constructor Variables

Say I have defined a Constructor and a prototype in Javascript like this:

MyGame.Player = function(){
this.somevar = 42;
};
MyGame.Player.prototype = {
somevar: null,
someFunc: function(){}
};


What will happen if I do the following:

MyGame.Player.Helper = function(){...}
MyGame.Player.Helper.prototype = {...}



  • Will javascript allow this actually?

  • Will the Helper appear as ownProperty in an instance of MyGame.Player() ?

  • Can I always create new Helper objects even if I don't have a Player object?


Answer

Will javascript allow this actually?

Sure. It's just a function as property of an object. In classical OOP this would be called a class method.

Will the Helper appear as ownProperty in an instance of MyGame.Player()?

Nope. It's a property of the constructor function, not of the instance. The instance only gets all properties assigned to this in the constructor and anything from the prototype. It doesn't inherit properties of the constructor function.

Can I always create new Helper objects even if I don't have a Player object?

Sure, because you call new MyGame.Player.Helper, not new (new MyGame.Player).Helper.

Put another way, you just assigned a function to MyGame.Player.Helper, of course you can call it via MyGame.Player.Helper(), because that's where you just put it.