0

I have two very simple prototypes in Javascript; however, when attempting to ensure one prototype inherits from the other, I am seeing behavior I don't understand. I am following Mozilla Developer Network's article on inheritance:

const Model = function (data) {
    this.doSomething(data);
};

Model.prototype.doSomething = function (data) {
    console.log("something");
};

// Second "inheriting" model  
const Word = function (data) {
    Model.call(this, data);
};

// Example use:

let word = new Word({ literal: "duck" });

When my code executes the Model prototype's constructor, I get an error I do not understand in this context:

this.doSomething is not a function.

As this is a relatively simple use case of inheritance, it leads me to believe I am missing something, entirely, about the prototype chain.

Is it not possible to call a function defined on an iherited prototype from the inherited prototype's constructor?

Thomas
  • 6,291
  • 6
  • 40
  • 69
  • 1
    That isn't how inheritance works in JavaScript, there's no inheritance here at all. Word's prototype has nothing to do with Model's, you're simply invoking Model's constructor on an object that has nothing to do with Model. – user229044 Jan 08 '18 at 22:00
  • @meagar I suspected, as much; however, I've been following MDN's doc.s. I'll post the link. – Thomas Jan 08 '18 at 22:02
  • 1
    You need to keep reading the article, you haven't reached the part that actually involves inheritance, ie "Setting Teacher()'s prototype and constructor reference". – user229044 Jan 08 '18 at 22:04
  • *face palm* Ugh. – Thomas Jan 08 '18 at 22:12
  • 1
    It's a good question for those of us learning the object model behind JS. Not sure why you got down voted other then inherit negativity in the coding community. I learned from your question and the answer below. A.prototype = Object.create(B.prototype) is equivalent to class A: B – Juls May 13 '18 at 19:01

1 Answers1

3

You just miss the prototype chain

Word.prototype = Object.create(Model.prototype);

before you call

var w = new Word('foo');

const Model = function (data) {
    this.doSomething(data);
};

Model.prototype.doSomething = function (data) {
    console.log("something");
};

// Second "inheriting" model  
const Word = function (data) {
    Model.call(this, data);
};

Word.prototype = Object.create(Model.prototype);

var w = new Word('foo');
Wiktor Zychla
  • 47,367
  • 6
  • 74
  • 106
  • Is it the case, here, too, that I need to reset the `Word` constructor? i.e. `Word.prototype.constructor = Word`. – Thomas Jan 08 '18 at 22:09
  • 1
    Other questions cover this already, e.g. https://stackoverflow.com/questions/8453887/why-is-it-necessary-to-set-the-prototype-constructor. In short - you don't always need it. – Wiktor Zychla Jan 08 '18 at 22:11