JavaScript: constructor versus prototype

This was said earlier, 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 both basically do the same thing, right? The only difference is that the function someConstructor() raised, which means that I can call new instances before it is defined, if necessary, and var somePrototype can only be called after it is defined. Other than that, no difference?

+6
source share
2 answers

Differences between the two approaches (using Object.create() and calling the constructor):

Creature:

  • Object.create(somePrototype) creates a new object that creates a prototype of somePrototype ;
  • new someConstructor() creates an object using a constructor call. The prototype of obj2 is a simple object: new Object()

Inheritance of properties:

  • obj1 inherits the speak property, which is a function. If this property is changed in the somePrototype object, it will affect any objects created using Object.create(somePrototype) that inherit it.
    Object.keys(obj1) will return [] , because the object does not have its own properties.
  • obj2 contains its own property speak . Changing this property in one instance will not affect other instances created using new someConstructor() .
    Object.keys(obj2) will return ['speak'] as its listed property.

Constructor:

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

Lifting:

  • someConstructor raised to the top of the area in which it was created. Therefore, it can be used before declaring a function.
  • And I'm sure that somePrototype not inserted with an object literal, so it should be used after setting the value.

Check out this interesting post about the constructor property.

+6
source

Calling Object.create() creates an object and gives it the prototype you requested. The new call creates an object that is directly decorated with this constructor function.

The difference is that the object created by the constructor has its own property, the value of which is a function with console.log() . Calling Object.create() creates an object that inherits a similar function from the prototype object.

If you moved the first object to Object.keys() , you will not see the “talk” property; if you passed the second object you would have done.

+5
source

All Articles