Maizere Pathak
Maizere Pathak

Reputation: 299

Instance creation

var Vehicle = function Vehicle() {
 // ...
}

var vehicle = new Vehicle();

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

  1. It creates a new object.
  2. It sets the constructor property of the object to Vehicle.
  3. It sets up the object to delegate to Vehicle.prototype.
  4. It calls Vehicle() in the context of the new object.

What is that third point telling? Does it mean new object constructor prototype is set to function.prototype? What does delegate mean here?

Upvotes: 4

Views: 92

Answers (3)

Umur Kontacı
Umur Kontacı

Reputation: 35478

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 every object inherits from another object (prototype). When you call a property on an object, it first searches the property in its own scope, if it can't find it, goes up in the property chain.

Upvotes: 0

otakustay
otakustay

Reputation: 12405

You just consider delegate as reference, every object has an [[Prototype]] internal property, and it references to its constructor's prorotype, so:

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

This is a seudo code about what new operator is doing:

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

Upvotes: 1

Florian Margaine
Florian Margaine

Reputation: 60787

It means that:

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

So the methods available on Vehicle.prototype will be available to the vehicle object.

Upvotes: 2

Related Questions