override([parent], property, callback);
Override the behavior of existing functions.
-
parentis the object containing the function to be called, it can be:- omitted: the
windowobject is used; - a constructor function (e.g., String): its prototype is used;
- an object: used as it is.
- omitted: the
-
propertyis the name of the property ofparentto override, if it is a function thenproperty.nameis used. -
callbackis used to customize the behavior of the overriden function. The invocation is in the form:callback($control, argument_1, ...)$controlis an object with the following properies:original(argument_1, ...)is a reference to the original function;argumentsis 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
callbackand itsthisare 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, ">"]