Skip to content

Instantly share code, notes, and snippets.

@Williammer
Created June 7, 2014 02:56
Show Gist options
  • Select an option

  • Save Williammer/5993a96968928d300d05 to your computer and use it in GitHub Desktop.

Select an option

Save Williammer/5993a96968928d300d05 to your computer and use it in GitHub Desktop.
jsPatterns.chainedMethod.js - add new methods for an class-like object.
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