Search code examples
javascriptclassconstructorprototypeprototypal-inheritance

Javascript inheritance, member undefined


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.


Solution

  • 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);