Created
January 3, 2013 09:56
-
-
Save mrosati84/4442322 to your computer and use it in GitHub Desktop.
Augmenting an object's prototype using module pattern
This file contains hidden or 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
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<title></title> | |
</head> | |
<body> | |
<script type="text/javascript"> | |
// Object constructor | |
var Person = function (args) { | |
this.name = args.name || "Default name"; | |
this.surname = args.surname || "Default surname" | |
}; | |
// Augment prototype using module pattern | |
Person.prototype = (function () { | |
/* | |
* @return void | |
*/ | |
var sayHello = function () { | |
console.log("Hello!"); | |
}; | |
/* | |
* @return string | |
*/ | |
var getName = function () { | |
return this.name; | |
}; | |
// Return public methods | |
return { | |
sayHello: sayHello, | |
getName: getName | |
}; | |
}()); | |
// Create a new object | |
var john = new Person({ | |
name: "John", | |
surname: "Doe" | |
}); | |
// Test object's methods | |
john.sayHello(); | |
console.log("My name is", john.getName()); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment