//Example
var point = {x: 10, y: 20};
// With functions
var configuration = {
allowResize: true,
resize: function(width, height) {
if (this.allowResize) {
this.width = width;
this.height = height;
}
}
};
function createPoint(x, y) {
return {x: x, y: y};
}
var createSegment = function(pointA, pointB) {
function distance(axis) {
return Math.abs(this.a[axis] - this.b[axis]);
}
return {
a: pointA,
b: pointB,
getSize: function() {
var x = distance.call(this, 'x');
var y = distance.call(this, 'y');
return Math.sqrt(x * x + y * y);
}
}
};
var pointA = createPoint(1, 1);
var pointB = createPoint(5, 3);
var segment = createSegment(pointA, pointB);
console.log(segment.getSize());
function Car(model, wheels, maxSpeed) {
this.model = model;
this.wheels = wheels;
this.maxSpeed = maxSpeed;
this.velocity = 0;
this.accelerate = function() {
this.velocity += 10;
},
this.brake = function() {
this.velocity -= 10;
}
}
var car = new Car('mini', 4, 240);
console.log(car);
function Car(model, wheels, maxSpeed) {
this.model = model;
this.wheels = wheels;
this.maxSpeed = maxSpeed;
this.velocity = 0;
}
// Assigning properties to prototype object
Car.prototype.accelerate = function() {
this.velocity += 10;
};
Car.prototype.brake = function() {
this.velocity -= 10;
};
// Replacing prototype object with new one
Car.prototype = {
accelerate: function() {
this.velocity += 10;
},
brake: function() {
this.velocity -= 10;
}
};
// Crockford's shim
Object.create = function (o) {
function F() {}
F.prototype = o;
return new F();
};
// Optimized version: Reuse function F
Object.create = (function () {
function F() {} // created only once
return function (o) {
F.prototype = o; // reused on each invocation
return new F();
};
})();
var proto = {
sayHello: function() {
return "My name is " + this.name + " and I salute you!";
}
};
var someone = Object.create(proto);
someone.name = "Lenny";
console.log(someone.sayHello());