Skip to content

Instantly share code, notes, and snippets.

@davidsk
Last active May 23, 2017 10:20
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 davidsk/17ef72283fb13d9b7476ae1e930918f5 to your computer and use it in GitHub Desktop.
Save davidsk/17ef72283fb13d9b7476ae1e930918f5 to your computer and use it in GitHub Desktop.
// constructor function
function Foo(){
//public
this.name = "Bob";
// private
var self = this, // <-- assign 'this' within constructor to private variable to allow private methods access to the object members
x = 6;
// private function; can access private variables and functions, use private 'this' alias (self) to access public members
function privateHello(){
console.log("I am a private function");
return self.name; // Bob
}
// privileged; is public but can access private members and be accessed by public members
this.publicHello = function(){
console.log("I am a public function");
return privateHello();
}
}
// public function
// does not have access to private or public members
Foo.prototype.bar = function(){
return "bar";
};
// ALTERNATIVE PROTOTYPE PATTERN
// Foo.prototype = {
// bar: function(){
// console.log("bar");
// }
// };
var foo = new Foo();
console.log("foo.name: " + foo.name); // Bob
console.log("foo.x: " + foo.x); // undefined
console.log("foo.self: " + foo.self); // undefined
console.log("foo.bar: " + foo.bar()); // bar
console.log("foo.publicHello(): " + foo.publicHello()); // Bob
console.log("foo.privateHello(): " + foo.privateHello()); // TypeError
// based on information from http://javascript.crockford.com/private.html
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment