Extending JavaScript Functions
DISCLAIMER: This is actually a really terrible idea, and mostly just a thought experiment!
This is a pattern you can use to extend JavaScript Functions, including native functions.
For example, we’ll extend the join()
function of the Array
type and add some logging before passing control back to the native join()
function.
Array.prototype.join = (function(_super) {
// return our new `join()` function
return function() {
console.log("Hey, you called join!");
return _super.apply(this, arguments);
}; // Pass control back to the original join()
// by using .apply on `_super`
})(Array.prototype.join);
//
// Pass the original function into our
// immediately invoked function as `_super`
// which remains available to our new
// function thanks to JavaScript closures.