-
-
Save menacestudio/2026655 to your computer and use it in GitHub Desktop.
JS: Pro JS Design Patterns Sample Code
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
<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