0
function A(name, gender) {
    this.name = name;
    this.gender = gender;
}

A.prototype.speak = function() {
    alert('Calling from A ' + this.name);
};

function B(name, gender){
    this.name = name;
    this.gender = gender;
}

B.prototype.speak = function() {
    alert('Calling from B ' + this.name);
};

B.prototype = Object.create(A.prototype);
B.prototype.constructor = B;

var b = new B('shane', 'M');
console.log(b);
b.speak();
  1. Why does the prototype chain looks at the parent prototype methods than looking at the Child prototype method?
  2. Will my instance b only have the instance propeties and methods and not its prototype methods?

The code above prints "Calling from A Shane";

Shane
  • 5,517
  • 15
  • 49
  • 79
  • 1
    You are overwriting `B`s prototype with `B.prototype = Object.create(A.prototype);` – Nick Tomlin May 24 '15 at 23:18
  • @NickTomlin: That's fine, but should it still not print speak of B.. as per the Prototype Chain – Shane May 24 '15 at 23:22
  • it's exactly because of the prototype chain that things aren't working :) The way things are currently written, B's prototype _is_ A's prototype. I've added an answer that hopefully explains things. I've also added a jsbin to demonstrate. – Nick Tomlin May 24 '15 at 23:31
  • First set inheritance and then override. You can re use A constructor by calling it in B: A.call(this,name,gender) more on prototype can be found here: http://stackoverflow.com/a/16063711/1641941 – HMR May 24 '15 at 23:44

2 Answers2

2

The prototype chain works in the way that expect it to work, but you are overwriting the prototype of B with the prototype of A when you assign it with Object.create.

There is nothing magical about prototypical inheritance (confusing, yes, magical, no), it's just traversing up the prototype chain until it finds a matching method. By overwriting B's prototype you've removed B's version of speak from the chain.

To have things work out the way you intend (e.g. to have B inherit from A, but have it's own speak method), you'll need to overwrite the method from B after you've assigned the prototype:

B.prototype = Object.create(A.prototype);
B.prototype.constructor = B;

B.prototype.speak = function() {
    alert('Calling from B ' + this.name);
};

jsbin

an instance of B will have all the methods on its prototype, but you can additionally add instance only methods if you desire.

Nick Tomlin
  • 28,402
  • 11
  • 61
  • 90
1
  1. Because you are setting B.prototype.speak first but then you override it by setting the prototype equal to A.prototype
  2. It will also have its prototype methods
Max Meijer
  • 1,530
  • 1
  • 14
  • 23