Understanding the difference between Object.create() and the new operator.
2 min readOct 13, 2017
Why is it important to know the difference?
- You will run across code that is not the absolute most recent Javascript.
- To be a great developer you need to learn how to deal with all types of code. That includes old code!
- Underneath the hood, the class keyword introduced in ECMAScript 6 utilizes the new operator behind the scenes.
Let’s start by examining what Object.create does:
var dog = {
eat: function() {
console.log(this.eatFood)
}
};
var maddie = Object.create(dog);
console.log(dog.isPrototypeOf(maddie)); //true
maddie.eatFood = 'NomNomNom';
maddie.eat(); //NomNomNom
Let’s go step by step through the above example and see what exactly is happening.
- Create an object literal named dog which has a single method called eat.
- Initialize maddie using Object.create(dog), which creates a completely new object with its prototype set to dog.
- Test to see if dog is a prototype of maddie.
- Set the string to be output via this.eatFood
- Call the eat function with the newly created object, maddie.
- Javascript will go through the prototype chain and find the eat method on dog with the “this” keyword set to maddie.
- Outputs NomNomNom in console.