Skip to content

Instantly share code, notes, and snippets.

@mrosati84
Created January 3, 2013 09:56
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 mrosati84/4442322 to your computer and use it in GitHub Desktop.
Save mrosati84/4442322 to your computer and use it in GitHub Desktop.
Augmenting an object's prototype using module pattern
<!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