Created
March 6, 2011 13:48
-
-
Save yuya-takeyama/857296 to your computer and use it in GitHub Desktop.
Encapsulated constructor in JavaScript.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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