Skip to content

Instantly share code, notes, and snippets.

@kentbrew
Created January 25, 2011 03:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save kentbrew/794462 to your computer and use it in GitHub Desktop.
Save kentbrew/794462 to your computer and use it in GitHub Desktop.
Pro JS Design Patterns Sample Code
<html>
<head>
<title>Chapter 6 Section 4, Pro JavaScript Design Patterns</title>
</head>
<body>
<script>
// this is straight from the code exampes at http://jsdesignpatterns.com/
// sadly, it fails with a syntax error. quoth JSLint:
//
// Error:
// Problem at line 6 character 12: Label 'setName' on 'function' statement.
// setName: function(newName) {
// Problem at line 6 character 20: Missing name in function statement.
// setName: function(newName) {
// Problem at line 9 character 4: Expected an identifier and instead saw ','.
// },
// Accessor without function callbacks: returning requested data in accessors.
window.API = window.API || {};
API.prototype = function() {
var name = 'Hello world';
// Privileged mutator method.
setName: function(newName) {
name = newName;
return this;
},
// Privileged accessor method.
getName: function() {
return name;
}
}();
// Implementation code.
var o = new API;
console.log(o.getName()); // Displays 'Hello world'.
console.log(o.setName('Meow').getName()); // Displays 'Meow'.
// Accessor with function callbacks.
window.API2 = window.API2 || {};
API2.prototype = function() {
var name = 'Hello world';
// Privileged mutator method.
setName: function(newName) {
name = newName;
return this;
},
// Privileged accessor method.
getName: function(callback) {
callback.call(this, name);
return this;
}
}();
// Implementation code.
var o2 = new API2;
o2.getName(console.log).setName('Meow').getName(console.log);
// Displays 'Hello world' and then 'Meow'.
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment