Skip to content

Instantly share code, notes, and snippets.

@davidsp
Last active August 29, 2015 13:57
Show Gist options
  • Select an option

  • Save davidsp/9394220 to your computer and use it in GitHub Desktop.

Select an option

Save davidsp/9394220 to your computer and use it in GitHub Desktop.
List of Object patterns for js (extracted from The Principles of Object-Oriented JavaScript, by Nicholas C.Zakas)
function mixin(receiver, supplier) {
for (var property in supplier) {
if (supplier.hasOwnProperty(property)) {
receiver[property] = supplier[property]
}
}
return receiver;
}
var person = (function () {
//private stuff
var age = 25;
return {
//public stuff
name: "Nicholas",
getAge: function () {
return age;
},
growOlder: function () {
age++;
}
};
}());
//If you want private data to be shared across all instances (as if it were on the prototype)
var Person = (function () {
// everyone shares the same age
var age = 25;
function InnerPerson(name) {
this.name = name;
}
InnerPerson.prototype.getAge = function () {
return age;
};
InnerPerson.prototype.growOlder = function () {
age++;
};
return InnerPerson;
}());
//Object patterns extracted from the 6th chapter of The Principles of Object-Oriented JavaScript, by Nicholas C.Zakas.
//http://shop.oreilly.com/product/9781593275402.do
function Person(name) {
// variable only accessible inside of the Person constructor
var age = 25;
this.name = name;
this.getAge = function () {
return age;
};
this.growOlder = function () {
age++;
};
}
var person = (function () {
var age = 25;
function getAge() {
return age;
}
function growOlder() {
age++;
}
return {
name: "Nicholas",
getAge: getAge,
growOlder: growOlder
};
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment