0

I think I'm probably doing something silly, but I'm not sure...

I have these two classes:

function Sprite()
{
}

Sprite.prototype.test1 = function()
{
    console.log("test1");
}

function Player()
{
}

Player.prototype.test2 = function()
{
    console.log("test2");
}

Player.prototype = new Sprite();
var player = new Player();

player.test1(); // this works
player.test2(); // this doesn't work..

I'm struggling to understand why test2() doesn't work, but test1() does work. If I add properties to these classes then I can access properties from both of them, I just can't call methods from the player class. What am I doing wrong?

1
  • you over-write Player.prototype.test2 when you assign a whole object to Player.prototype. If you defined test2 after, it would create the method on the new object instead, and both would work. Commented Feb 9, 2017 at 19:55

1 Answer 1

1

When you do this:

Player.prototype.test2 = function()
{
     console.log("test2");
}

Player.prototype = new Sprite(); // Original Player.prototype gets overwritten here

You first modify a property of Player.prototype, then you reassign Player.prototype to a new object, losing the original prototype of Player.

If you reverse the order of those 2 statements, your test will pass.

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

Comments

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.