0

I'm making a "class" in a file called Animation.js:

function Animation(s) {
  this.span = s;
};

Animation.prototype = Object.create(Animation.prototype);
Animation.prototype.constructor = Animation;

And I create a child class which is in a file called LinearAnimation.js:

function LinearAnimation(s, cP) {
     Animation.call(s);
     this.controlPoints = cP;
};

LinearAnimation.prototype = Object.create(Animation.prototype);
LinearAnimation.prototype.constructor = LinearAnimation;

The problem is, when I access to this.span member in the LinearAnimation class it says it's undefined. Am I implementing this well? Thank you.

2
  • 3
    At a glance, you probably want Animation.call(this, s), not Animation.call(s). The first argument to call sets this for the function invocation. Commented Nov 5, 2015 at 19:26
  • 3
    Animation.prototype = Object.create(Animation.prototype); is probably not what you wanted either. Commented Nov 5, 2015 at 19:26

2 Answers 2

5

The Function.prototype.call() function takes a thisArg as it's first argument, meant to be the this inside the called function. After that, any other argument(s) is(are..) passed as input to the called function.

Also, there's no point in replacing the prototype of a function (class) with an object inherited from itself.

Try this:

function Animation(s) {
  this.span = s;
};

function LinearAnimation(s, cP) {
     Animation.call(this, s);
     this.controlPoints = cP;
};
LinearAnimation.prototype = Object.create(Animation.prototype);
LinearAnimation.prototype.constructor = LinearAnimation;

var la = new LinearAnimation('something', [1, 2, 3]);

console.log(la);

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

Comments

2

You want Animation.call(this, s), not Animation.call(s). The first argument to call sets this for the function invocation. In your code, you're calling Animation with a this of s, so your s argument gets a span property, rather than the this being constructed in LinearAniamtion.

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.