override([parent], property, callback);
Override the behavior of existing functions.
-
parent
is the object containing the function to be called, it can be:- omitted: the
window
object is used; - a constructor function (e.g., String): its prototype is used;
- an object: used as it is.
- omitted: the
-
property
is the name of the property ofparent
to override, if it is a function thenproperty.name
is used. -
callback
is used to customize the behavior of the overriden function. The invocation is in the form:callback($control, argument_1, ...)
$control
is an object with the following properies:original(argument_1, ...)
is a reference to the original function;arguments
is a proper array of the arguments passed to the original function;replay()
is an helper function which is equivalent to calling the original funtion with the arguments currently specified in$control.arguments
.
argument_1, ...
are the arguments passed to the original function.The return value of
callback
and itsthis
are the same as the original function.
// Hijack the default behavior.
override(alert, function ($control, message) {
console.log('ALERT: "%s"', message);
});
alert(42); // ALERT: "42"
// Log all the requests.
override(XMLHttpRequest, 'open', function ($control, method, url) {
console.log('AJAX: %s %s', method, url);
return $control.replay();
});
var ajax = new XMLHttpRequest();
ajax.open('GET', 'http://example.com'); // GET http://example.com
ajax.send();
// Hijack the return value.
override(Object, 'toString', function () {
return 'lollo';
});
({}).toString(); // lollo
// Change some parameters #1.
override(String, 'replace', function ($control, subStr, newSubStr, flags) {
newSubStr = '/*' + newSubStr + '*/';
return $control.original(subStr, newSubStr, flags);
});
'foo bar baz'.replace('bar', 'xxx'); // "foo /*xxx*/ baz"
// Change some parameters #2.
override(Array, function ($control) {
$control.arguments.unshift('<');
$control.arguments.push('>');
return $control.replay();
});
new Array(1,2,3); // ["<", 1, 2, 3, ">"]