2

Could some javascript ninja explain to me why my constructor is botched here? I feel like I'm implementing the prototype chain correctly. I know I could use Object.create, but I'm just interested in understanding why this doesn't work.

var Vehicle = function() {}
Vehicle.prototype.accelerate = function() { console.log('VRRRROOOOOOOM') }
Vehicle.prototype.brake = function() { console.log('SCREEEEECH') }

var Car = function() {}
Car.prototype = new Vehicle
Car.prototype.openTrunk = function() { console.log('POP') }
Car.prototype.closeTrunk = function() { console.log('CLUNK') }

// Test
var mazda = new Car
console.log(mazda) // prototype chain is right
console.log(mazda.constructor === Car) // should be true
console.log(mazda.constructor === Vehicle) // should be false

https://jsfiddle.net/6j43r8qg/1/

savinger
  • 6,544
  • 9
  • 40
  • 57

2 Answers2

4

The constructor property is defined on the prototype.

Car.prototype = new Vehicle

overrides the prototype and assigns an instance of Vehicle to it. All Vehicle instances inherit constructor, which points to Vehicle, from Vehicle.prototype.

enter image description here

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • Thanks, that makes sense. But who's fault is this, mine or javascript's? – savinger Jun 25 '15 at 21:59
  • Yes. That's why you typically set `Child.prototype.constructor = Child;` after you overwrote the prototype. See [Why is it necessary to set the prototype constructor?](http://stackoverflow.com/q/8453887/218196) – Felix Kling Jun 25 '15 at 22:00
  • @SpencerAvinger: Not sure if one can speak of "fault" here. You overwrote `Child.prototype` which contained the `constructor` property. So I guess its your fault? – Felix Kling Jun 25 '15 at 22:03
  • In a perfect world, wouldn't the `prototype.constructor === Vehicle` and `mazda.constructor === Car`? Because Vehicle made Car.prototype, and Car made mazda? – savinger Jun 25 '15 at 22:06
  • 2
    I don't know. Maybe in a perfectly world `constructor` would not exist at all. – Felix Kling Jun 25 '15 at 22:08
0

Also I think instanceof would be the way to check if something is a something

console.log(mazda) // prototype chain is right
console.log(mazda instanceof Car) // should be true
console.log(mazda instanceof Vehicle) // should be *true?!*
Mark Knol
  • 9,663
  • 3
  • 29
  • 44