Saturday, June 4, 2016

Object.create and prototype confusions

This is a topic that I like to give anyone interviewing for a JS position at my company. It's a bit of a brain-twister, and unless you really understand how prototypal inheritance works in JS, there's a pretty good chance you'll get it wrong.

What's the difference between:

1. var objB = Object.create(objA);

and

2. var objB = new objA();

When we write #1, objB's internal [[proto]] property points to the object that is objA. That means that when we execute something like:

var objA = {
  a:42;
}
var objB = Object.create(objA); //objB.__proto__ === objA
console.log(objB.a); 

However, when we have the following scenario, invoking a function as a constructor:

function objA(){
  this.a = 42;
}
objA.prototype.b = 43;
var objB = new objA(); //objB.__proto__ === objA.prototype
console.log(objB.a); //42
console.log(objB.b); //43
console.log(objB.__proto__); //objA.prototype

So we see that when when use the new keyword with a function, the object that is created (objB) has it's internal [[proto]] pointing to the function's prototype property (objA.prototype).

No comments:

Post a Comment