Skip to content

Instantly share code, notes, and snippets.

@davidsk davidsk/javascriptModule
Last active May 23, 2017

Embed
What would you like to do?
// 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
You can’t perform that action at this time.