Last active
December 17, 2015 11:09
-
-
Save artsobolev/5599917 to your computer and use it in GitHub Desktop.
Namespaced Methods for [built-in types] in JavaScript
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
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