function Message(subject, recipient, content) {
this.subject = subject;
this.recipient = recipient;
this.content = content;
}
Message.prototype.show = function(){
console.log('To:' + this.recipient + 'Subject: ' + this.subject + 'Message:' + this.content);
};
var myEmail = new Message('Javascript is cool', '[email protected]', 'Prototype is useful');
function Stack() {
this.dataStore = [];
this.top = 0;
this.push = push;
this.pop = pop;
this.peek = peek;
this.clear = clear;
this.length = length;
}
function push(element) {
this.dataStore[this.top++] = element;
}
function peek() {
return this.dataStore[this.top-1];
}
function pop() {
return this.dataStore[--this.top];
}
function clear() {
this.top = 0;
}
function length() {
return this.top;
}
From "The Principles of Object-Oriented JavaScript" (http://proquest.safaribooksonline.com/book/programming/javascript/9781457185304/6dot-object-patterns/scope_safe_constructors_html#X2ludGVybmFsX0h0bWxWaWV3P3htbGlkPTk3ODE0NTcxODUzMDQlMkZjb25zdHJ1Y3RvcnNfaHRtbCZxdWVyeT0=)
The following pattern protects from accidentally doing:
person = Person("frank");
without the new operator
function Person(name) {
if (this instanceof Person) {
this.name = name;
} else {
// called without "new", throw exception or something...
}
}
Person.prototype.sayName = function() {
console.log(this.name);
};
From code pen blog post (http://codepen.io/rachsmith/blog/controlling-the-canvas-with-javascript-objects):
function Circle(x,y,rad,color) {
var _this = this;
// constructor
(function() {
_this.x = x || null;
_this.y = y || null;
_this.radius = rad || null;
_this.color = color || null;
})();
this.draw = function(ctx) {
if(!_this.x || !_this.y || _this.radius || _this.color) {
console.error('Circle requires an x, y, radius and color');
return;
}
ctx.beginPath();
ctx.arc(_this.x, _this.y, _this.radius, 0, 2 * Math.PI, false);
ctx.fillStyle = _this.color;
ctx.fill();
}
}
From "Essential JS Design Patterns" (The Module Pattern) (http://addyosmani.com/resources/essentialjsdesignpatterns/book/#constructorpatternjavascript)
var testModule = (function () {
var counter = 0;
return {
incrementCounter: function () {
return counter++;
},
resetCounter: function () {
console.log( "counter value prior to reset: " + counter );
counter = 0;
}
};
})();
// Usage:
// Increment our counter
testModule.incrementCounter();
// Check the counter value and reset
// Outputs: 1
testModule.resetCounter();
http://dailyjs.com/2012/06/04/js101-object-create/