Search code examples
javascriptinheritanceprototypethiscode-reuse

Prototypical Chaining in JavaScript


Currently trying to add $1 to my Tween every time the makeMoney method is called but instead I receive an error that the makeMoney method is not a function. I have a hunch that it has to do with this but I have tried to bind 'this' to the makeMoney method to no avail. This truly seems like it should be simple but I am coming up empty.

var Tween = function() {
    Adolescent.call(this);
    this.age  =  12;
    this.job = 'annoy';
    this.allowance = 5;

};
Tween.prototype.makeMoney = function(){

    return this.allowance ++;
}

Tween.prototype = Object.create(Adolescent.prototype);
Tween.prototype.constructor = Tween;

Solution

  • What you're doing here is first you're adding function to the prototype of the object Tween, and then, you're overwriting whole prototype object with Object.create(Adolescent.prototype). That is why it's undefined.

    Instead do the inheritance before extending the prototype.

    var Tween = function() {
        Adolescent.call(this);
        this.age  =  12;
        this.job = 'annoy';
        this.allowance = 5;
    
    };
    
    Tween.prototype = Object.create(Adolescent.prototype);
    Tween.prototype.constructor = Tween;
    
    Tween.prototype.makeMoney = function(){
    
        return this.allowance ++;
    }