Taylor Huston Taylor Huston - 7 months ago 17
Javascript Question

JavaScript: Constructor vs Prototype

This has been answered before, but I wanted to confirm my understanding. In this code:

var somePrototype = {
speak: function() {
console.log("I was made with a prototype");
}
}

function someConstructor() {
this.speak = function() {
console.log("I was made with a constructor");
}
}

var obj1 = Object.create(somePrototype);
var obj2 = new someConstructor();

obj1.speak();
obj2.speak();


They are both fundamentally doing the same thing, correct? The only difference is that the
function someConstructor()
is hoisted, meaning I can call new instances of it before it is defined, if needed, while the
var somePrototype
can only be called after it's been defined. Other than that, there's no difference?

Answer

The differences between 2 approaches (using Object.create() and constructor invocation) are:

The creation:

  • Object.create(somePrototype) creates a new object making the somePrototype it's prototype;
  • new someConstructor() creates an object using constructor invocation. The prototype of the obj2 is a simple object: new Object()

The properties inheritance:

  • obj1 inherits the property speak, which is a function. If this property changes in the somePrototype object, this will affect any objects created with Object.create(somePrototype) which inherit it.
    Object.keys(obj1) will return [], because the object has no own properties.
  • obj2 contains an own property speak. Modifying this property on a single instance won't affect any other instances created using new someConstructor().
    Object.keys(obj1) will return ['speak'].

The constructor:

  • obj1.constructor === Object is true
  • obj2.constructor === someConstructor is true

Hoisting:

  • someConstructor is hoisted to the top of scope it was created. So it can be used before the function declaration.
  • And sure somePrototype is not hoisted with the object literal, so should be used after setting up the value.

Check this interesting post about constructor property.

Comments