Created
April 13, 2010 04:51
-
-
Save yuya-takeyama/364324 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/** | |
* Private members in JavaScript | |
* | |
* @author Yuya Takeyama | |
*/ | |
var Dog = (function () { | |
var Dog, | |
privateNameSpace = {}; | |
/** | |
* Constructor | |
* Create a new dog and name it. | |
* Then private namespace is created also. | |
* | |
* @class A class represents Dogs. | |
* @param {String} name The dog's name | |
* @param {Number} age The dog's age | |
*/ | |
Dog = function (name, age) { | |
var d = new Date; | |
/** | |
* Identifier of the Dog object. | |
* @type String | |
*/ | |
this.objectId = '' + d.getTime() + Math.random(); | |
// Create a private namespace | |
privateNameSpace[this.objectId] = {}; | |
privateNameSpace[this.objectId].name = name; | |
privateNameSpace[this.objectId].age = age; | |
}; | |
/** | |
* Read-accessor of the dog's name. | |
* | |
* @return {String} The dog's name. | |
*/ | |
Dog.prototype.getName = function () { | |
return privateNameSpace[this.objectId].name; | |
}; | |
/** | |
* Read-accessor of the dog's age. | |
* | |
* @return {Number} The dog's age. | |
*/ | |
Dog.prototype.getAge = function () { | |
return privateNameSpace[this.objectId].age; | |
}; | |
return Dog; | |
})(); |
This file contains hidden or 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 pochi = new Dog('Pochi', 5); | |
var taro = new Dog('Taro', 12); | |
window.alert(pochi.getName() + ' is ' + pochi.getAge() + ' years old.'); | |
// => Pochi is 5 years old. | |
window.alert(taro.getName() + ' is ' + taro.getAge() + ' years old.'); | |
// => Taro is 12 years old. |
This file contains hidden or 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 pochi = new Dog('Pochi', 5); | |
var taro = new Dog('Taro', 12); | |
window.alert(pochi.getName() + ' is ' + pochi.getAge() + ' years old.'); | |
// => Pochi is 5 years old. | |
window.alert(taro.getName() + ' is ' + taro.getAge() + ' years old.'); | |
// => Taro is 12 years old. | |
// ObjectId jacking. | |
pochi.objectId = taro.objectId; | |
window.alert(pochi.getName() + ' is ' + pochi.getAge() + ' years old.'); | |
// => Taro is 12 years old. | |
window.alert(taro.getName() + ' is ' + taro.getAge() + ' years old.'); | |
// => Taro is 12 years old. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment