Skip to content

Instantly share code, notes, and snippets.

@yuya-takeyama
Created March 6, 2011 13:48
Show Gist options
  • Save yuya-takeyama/857296 to your computer and use it in GitHub Desktop.
Save yuya-takeyama/857296 to your computer and use it in GitHub Desktop.
Encapsulated constructor in JavaScript.
var Dog = (function () {
var init, create;
/**
* Encapsulated Constructor,
*/
init = function (name, age) {
this.name = name;
this.age = age;
};
/**
* Public Constructor.
*
* @param {String} name The dog's name.
* @param {Number} age The dog's age.
*/
create = function (name, age) {
return new init(name, age);
};
/**
* Instance methods.
* These are encapsulated too.
*/
init.prototype = {
/**
* Prints the dog's greeting.
*
* @return {void}
*/
greet : function () {
print("My name is " + this.name + ". " +
"I'm " + this.age + " years old.");
}
};
return {
create : create
};
})();
var pochi = Dog.create('Pochi', 3);
pochi.greet();
// => My name is Pochi. I'm 3 years old.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment