Search code examples
javascriptnode.jsprototype

javascript inheritance by prototype chaining didnt working


I follow the book of Stoyan Stefanov JavaScript Patterns ans have a stuck... I cant inherit the prototype. Why? What I do wrong? (run this code on NodeJS)

// inheritance
function Parent(name) {
  this.name = name || 'some Name';
}

Parent.prototype.say = () => this.name;

function Child(name) {
  // this.name = '123';
}

function inherit(C, P) {
  C.prototype = new P();
}
inherit(Child, Parent);
debug(Child.prototype);

const kid = new Child();
debug(kid);
debug(kid.name);
debug(kid.say());

Solution

  • Arrow functions are not intended to be used as methods. Parent.prototype.say should be normal function instead. From MDN

    An arrow function expression has a shorter syntax than a function expression and does not have its own this, arguments, super, or new.target. These function expressions are best suited for non-method functions, and they cannot be used as constructors.

    // inheritance
    function Parent(name) {
      this.name = name || 'some Name';
    }
    
    Parent.prototype.say = function() { // normal function
      return this.name;
    };
    
    function Child(name) {
      // this.name = '123';
    }
    
    function inherit(C, P) {
      C.prototype = new P();
    }
    inherit(Child, Parent);
    console.log(Child.prototype);
    
    const kid = new Child();
    console.log(kid);
    console.log(kid.name);
    console.log(kid.say());