Created
June 7, 2014 02:56
-
-
Save Williammer/5993a96968928d300d05 to your computer and use it in GitHub Desktop.
jsPatterns.chainedMethod.js - add new methods for an class-like object.
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
| if (typeof Function.prototype.method !== "function") { | |
| Function.prototype.method = function (name, implementation) { | |
| this.prototype[name] = implementation; | |
| return this; // enable chaining function. | |
| }; | |
| } | |
| var Person = function (name) { | |
| this.name = name; | |
| }. | |
| method('getName', function () { | |
| return this.name; | |
| }). | |
| method('setName', function (name) { | |
| this.name = name; | |
| return this; | |
| }); | |
| var p = new Person(), | |
| name = p.setName('william').getName(); | |
| var div = document.createElement('div'); | |
| div.className = 'container'; | |
| div.style.fontSize = '12px'; | |
| div.style.color = 'red'; | |
| div.innerHTML = name; | |
| document.body.appendChild(div); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment