0

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?
2
  • 2
    Have you tried it out ? Commented Jun 23, 2016 at 9:24
  • Before using it I just wanted to make sure that there is nothing bad or dangerous about doing so :D Commented Jun 23, 2016 at 9:41

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@Brian Have a look at standard Javascript objects: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…, they're clearly segregated into "Methods" and "Instance/Prototype methods". Same thing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.