Skip to content

Instantly share code, notes, and snippets.

@dennisseah
Created August 24, 2014 22:39
Show Gist options
  • Save dennisseah/e9e74b7a55816dba2628 to your computer and use it in GitHub Desktop.
Save dennisseah/e9e74b7a55816dba2628 to your computer and use it in GitHub Desktop.
Javascript: Module Pattern to define a class
// Javascript module pattern to define class
// having private and public members and functions
var Cat = (function() {
// private member
var _name = null;
// constructor
function Cat(name) {
_name = name; // this one is private
this.name = name; // this one is public
}
// private method
var _speak = function() {
return 'meow';
};
// public method
Cat.prototype.speak = function() {
return 'I say ' + _speak();
};
// public method
Cat.prototype.sayYourName = function() {
return 'I am ' + _name;
};
return Cat;
}());
var cat = new Cat('Alice');
console.log(cat.speak());
console.log(cat.sayYourName());
console.log(cat.name);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment