Skip to content

Instantly share code, notes, and snippets.

@levi
Created November 16, 2012 02:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save levi/4083325 to your computer and use it in GitHub Desktop.
Save levi/4083325 to your computer and use it in GitHub Desktop.
Private Members and Privileged Methods in Constructors and Objects
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