Reputation: 299
var Vehicle = function Vehicle() {
// ...
}
var vehicle = new Vehicle();
When new Vehicle() is called, JavaScript does four things:
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
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
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
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