Skip to content

Instantly share code, notes, and snippets.

@artsobolev artsobolev/nsProto.js
Last active Dec 17, 2015

Embed
What would you like to do?
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
You can’t perform that action at this time.