Skip to content

Instantly share code, notes, and snippets.

@artsobolev
Last active December 17, 2015 11:09
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 artsobolev/5599917 to your computer and use it in GitHub Desktop.
Save artsobolev/5599917 to your computer and use it in GitHub Desktop.
Namespaced Methods for [built-in types] in JavaScript
function extendPrototype(Class, name, obj) {
var nsProto = {},
self = null;
for (var prop in obj) {
if(!obj.hasOwnProperty(prop)) continue;
Object.defineProperty(nsProto, prop, {
enumerable: true,
configurable: false,
get : function() {
return function() {
return obj[prop].apply(self, arguments);
};
}
});
}
Object.defineProperty(Class.prototype, name, {
enumerable: false,
configurable: false,
get : function() {
self = this;
return nsProto;
}
});
};
extendPrototype(String, "utils", {
append : function(tail) {
return this + tail;
}
});
extendPrototype(Number, "rubish", {
times : function(callback) {
var n = this;
for (var i = 0; i < n; ++i) {
callback();
}
}
});
// Example
2..rubish.times(function() {
console.log("One more iteration");
console.log('Hello'.utils.append(' World'));
console.log('Hello'.utils.append(' World')
.utils.append('!'));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment