var obj = {
hello: 'world',
id: 1234
};
var obj = new Object();
obj.hello = 'world';
obj.id = 1234;
var obj = Object.create(null, {
hello: { value: "world" },
id: { value: 1234 }
});
var carInstance = {
drive: function(direction) { ... },
stop: function() { ... }
speed: 65
mileage: 80000
};
function Car() {
var wearAndTear = 0;
function startEngine() {
...
}
function turn() {
..
}
return {
drive: function(direction) { ... }
stop: function() { ...},
speed: 0,
mileage: 0
}
}
Create an instance with
var carInstance = Car();
function Car() {
var wearAndTear = 0;
function startEngine() {
...
}
function turn() {
..
}
this.drive = function(direction) { ... };
this.stop = function() { ...};
this.speed = 0;
this.mileage = 0;
}
Create an instance with
var carInstance = new Car();
A function’s prototype is the object instance that will become the prototype for all objects created using this function as a constructor.
// *** function Object() {} ***
Object.prototype --> {} .prototype --> null
// What about var obj = new Object()?
obj.prototype --> {} .prototype --> null
// What about function Array(length) {} ?
(Same as Object.prototype)
Array.prototype --> {} .prototype --> {} .prototype --> null
var Car = (function() {
function Car() {
this.speed = 0;
this.mileage = 0;
// Pseudo private variable
this._wearAndTear = 0;
}
function startEngine() {
...
}
function turn() {
..
}
Car.prototype.drive = function(direction) { ... };
Car.prototype.stop = function() { ...};
Car.prototype.speed = 0;
Car.prototype.mileage = 0;
})();
Create an instance with
var carInstance = new Car();
Build upon what is already available
Prototype, Prototype, Prototype
Our new car
function Truck() { }
// Common mistake
Truck.prototype = Car.prototype;
What's wrong?
function Truck() { }
Truck.prototype = new Car();
Truck.prototype.openTailgate = function() { ... }
...
function inherit(Parent, Child) {
function Temp() { this.constructor = Child; }
Temp.prototype = Parent.prototype;
Child.prototype = new Temp();
}
// Also called extend
function mixin(obj, otherObj) {
for (var key in otherObj) {
obj[key] = otherObj[key];
}
}
// Broadcasts events (simple pub/sub)
function Broadcaster() {}
Broadcaster.prototype.listen = function(event, fn) { ... };
Broadcaster.prototype.broadcast = function(event, data) { ... };
function Car() {
extend(this, new Broadcaster());
}
Car.prototype.drive = function(direction) {
if(obstruction) {
this.broadcast('error', { errorMsg: 'Obstruction!'});
}
}