0

I am expecting my console.log to print "Creature and Charles" however it only prints Creature:

function creature() {}
creature.prototype.name = 'Creature';
creature.prototype.showName = function () {
    return this.constructor.uber ? this.constructor.uber.toString() + ',' + this.name : this.name;
}

function dog() {}
var F = function () {}
dog.prototype = new F();
dog.prototype.constructor = dog;
dog.prototype.name = 'Charles';
dog.uber = creature.prototype;
dog.prototype = creature.prototype;
var cat = new dog();
console.log(cat.showName());

Any help?

j08691
  • 204,283
  • 31
  • 260
  • 272
Aessandro
  • 5,517
  • 21
  • 66
  • 139
  • Should the dog.uber allow to print Charles too? – Aessandro Apr 10 '15 at 16:00
  • 2
    You're overwriting the previous lines `dog.prototype = creature.prototype;`, so no it shouldn't. – Artjom B. Apr 10 '15 at 16:07
  • 1
    Is `uber` anything but a randomly named property, or why is it mentioned in question title? – CBroe Apr 10 '15 at 16:52
  • http://www.crockford.com/javascript/inheritance.html – Aessandro Apr 10 '15 at 18:06
  • 1
    DC has yet to produce code that implement what he calls "classical inheritance" correctly. Maybe the following answer can explain the things he and you are doing wrong: http://stackoverflow.com/a/16063711/1641941 the following book is also very good: https://github.com/getify/You-Dont-Know-JS/blob/master/README.md – HMR Apr 10 '15 at 23:51

1 Answers1

0

I would can suggest you make all manipulations with dog prototype little bit simple:

function creature() {}
creature.prototype.name = 'Creature';
creature.prototype.showName = function () {
    return this.constructor.uber ? this.constructor.uber.showName() +
      ',' + this.name : this.name;
}

function dog() {}
dog.prototype = Object.create(creature.prototype);
dog.prototype.constructor = dog;
dog.prototype.name = 'Charles';
dog.uber = creature.prototype;
var cat = new dog();
console.log(cat.showName());
Pencroff
  • 1,009
  • 9
  • 13
  • 1
    Setting the Child prototype to an instance of Parent shows a lack of understanding what prototype is. new Parent creates a Parent instance with initialized instance members that are now on Child.prototype and shared among all Child instances. Maybe the following answer can explain why it is a bad idea in more detail: http://stackoverflow.com/a/16063711/1641941 – HMR Apr 10 '15 at 23:55