0

Need your help to understand what is the Difference between Prototype and Object.create Inheritance ?. Please some one please describe why console.log(objBird.a()); is giving error.

ref: https://jsfiddle.net/_private/4bmnctoz/

Code:

(function(){
  console.clear();
  var Living = function() {
    var livingCell = 'I am living !';
    this.isLiving = function() {
      return livingCell;
    }
  };
  Living.prototype.a = function() {
    return 'here !!';  
  };
  var objLiving = new Living();
    console.log(objLiving.isLiving());


  var Animal = function() {
    var data = 'I am animal !';
    this.express = function() {
      return data;
    };
  };
  Animal.prototype = new Living();
  Animal.prototype.constructor = Animal;
  var objAnimal = new Animal();
  console.log(objAnimal.express());
  console.log(objAnimal.a());
  console.log(objAnimal.isLiving());

  var Bird = function() {
     var data = 'I am bird !';
    this.express = function() {
      return data;
    };
  };
  var objBird = new Bird();
  objBird.prototype = Object.create(Living);
  objBird.prototype.constructor = Bird;
  console.log(objBird.express());
  console.dir(objBird);
  console.log(objBird.a());
})();
asishkhuntia
  • 417
  • 1
  • 4
  • 7
  • *"Please some one please describe why console.log(objBird.a()); is giving error."* Because you are creating `objBird` **before** you are setting up the prototype chain. If you put `var objBird = new Bird();` *after* `objBird.prototype.constructor = Bird;`, calling `objBord.a()` will work. Also, both of these ways are "prototype inheritance". The only difference is *how* the prototype object is created. Using `Object.create` is the more reliable way. – Felix Kling Sep 09 '17 at 21:42
  • Because the prototype is attached to a function, not an object. The whole point of the prototype is to share methods between objects. So placing a prototype on a single object really doesn't make much sense, your may as well do `object.property = prop` – Keith Sep 09 '17 at 21:45
  • @FelixKling `var objBird = new Bird(); after objBird.prototype.constructor = Bird;` that will of course give `objBird is not defined` – Keith Sep 09 '17 at 21:52
  • @Keith: Doh, of course. It should be `Bird.prototype...` instead. But the instance still has to be created after assigning to that property. – Felix Kling Sep 09 '17 at 21:53
  • Thanks @FelixKling, made those changes that issue solved.. but still not inherits all method – asishkhuntia Sep 09 '17 at 22:01

0 Answers0