Created
November 16, 2012 02:15
-
-
Save levi/4083325 to your computer and use it in GitHub Desktop.
Private Members and Privileged Methods in Constructors and Objects
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
function Animal() { | |
var name = 'Lion'; | |
// privileged method | |
this.getName = function() { | |
return name; | |
}; | |
} | |
var lion = new Animal(); | |
console.log(lion.getName() === 'Lion'); | |
console.log(lion.name === void 0); | |
// Object literals | |
var obj; | |
(function() { | |
var name = 'bob lob law'; | |
obj = { | |
getName: function() { | |
return name; | |
} | |
}; | |
})(); | |
console.log(obj.getName() === 'bob lob law'); | |
var altObj = (function() { | |
var name = 'gob bluth'; | |
return { | |
getName: function() { | |
return name; | |
} | |
}; | |
})(); | |
console.log(altObj.getName() === 'gob bluth'); | |
// Private members in the prototype property object for better performance | |
function Device() { | |
var name = 'Nintendo Wii'; | |
this.getName = function() { | |
return name; | |
}; | |
} | |
Device.prototype = (function() { | |
var type = 'console'; | |
return { | |
getType: function() { | |
return type; | |
} | |
}; | |
})(); | |
var wii = new Device(); | |
console.log(wii.getName() === 'Nintendo Wii'); | |
console.log(wii.getType() === 'console'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment