Instantiation

var Vehicle = function Vehicle() { // ... } var vehicle = new Vehicle(); 

When a new Vehicle () is called, JavaScript does four things:

  • He creates a new object.
  • It sets the constructor property of the Vehicle object.
  • It sets the object for delegation in Vehicle.prototype.
  • It calls Vehicle () in the context of the new object.

What is this third point? Does this mean that the prototype of the object constructor is set as function.prototype? What does the delegate mean here?

+4
source share
3 answers

You consider delegating as reference , each object has an internal [[Prototype]] property and refers to its constructor , therefore

 Object.getPrototypeOf(vehicle) === Vehicle.prototype; // always true 

This is the seudo code about what the new operator does:

 function fakeNew(constructor) { var instance = {}; instance.__proto__ = constructor.prototype; instance.constructor = constructor; constructor.apply(instance, [].slice.call(arguments, 1)); return instance; } 
+1
source

It means that:

 vehicle.constructor.prototype === Vehicle.prototype; // true 

Thus, the methods available in Vehicle.prototype will be accessible to the vehicle object.

+2
source
 var Vehicle = function Vehicle() { this.engine = {running:false}; } Vehicle.prototype.startEngine = function () { this.engine.running = true; }; var vehicle1 = new Vehicle(); vehicle.startEngine(); // vehicle.engine.running === true var vehicle2 = new Vehicle(); vehicle2.startEngine = function () { throw "err"; }; vehicle2.startEngine(); // Error: "err" 

Javascript is prototype-based, so each object is inherited from another object (prototype). When you call a property on an object, it first looks for the property in its scope, if it cannot find it, it grows in the property chain.

0
source

All Articles