Created
August 24, 2014 22:39
-
-
Save dennisseah/e9e74b7a55816dba2628 to your computer and use it in GitHub Desktop.
Javascript: Module Pattern to define a class
This file contains 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
// 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