I've been trying to wrap my head around the new Object.create
method which was introduced in ECMAScript 5.
Usually when I want to use inheritance I do something like this:
var Animal = function(name) { this.name = name; }Animal.prototype.print = function() { console.log(this.name); }var Dog = function() { return Animal.call(this, 'Dog'); }Dog.prototype = new Animal();Dog.prototype.bark = function() { console.log('bark'); }
I just assign a newly created Animal object to Dog's prototype and everything works like a charm:
var dog1 = new Dog();dog1.print(); // prints 'Dog'dog1.bark(); // prints 'bark'dog1.name; //prints 'Dog'
but people(without explaining) are saying that Dog.prototype = new Animal();
is not the way inheritance works and that I should use Object.create approach:
Dog.prototype = Object.create(Animal.prototype);
which also works.
What's the benefit of using Object.create
or am I missing something?
UPDATE: Some say that Dog.prototype = Animal.prototype;
can also work. So now I'm totally confused