I want to add additional functionality to a method, for instance:
console.log()
so the original 'log' functionality is retained, and I can get it to do something new as well. Is this possible? I've read a few bits on using prototype but haven't quite grasped it.
Many thanks,
It's very easy. If you want your new log mehod to be in place of the old log method just do something like that:
console._log = console.log; // just backing up old log method
console.log = function(){
console._log(arguments);
alert("I'm doing something else here");
}
console.log(console);
UPDATE:
All the solutions presented, including mine, didn't reproduced the log behavior perfectly as @TomBates stated. The output differed because arguments were being logged wrapped in an object instead of passed separately. The only way I could find to reproduce the behavior of the old log + the extending functionality was doing this:
console.log(window, this, console); // old log in action
console._log = console.log; // just backing up old log method
console.log = function(){
var args_string = '';
for(i in arguments){
if(arguments.hasOwnProperty(i)){
args_string += 'arguments['+ i + ']';
if(i != arguments.length - 1){
args_string += ',';
}
}
}
var expression = 'console._log(' + args_string + ');';
eval(expression);
alert("I'm doing something else here");
// your dazzling method extension here
}
console.log(window, this, console); //new log in action
Not so elegant, but works as expected. the outputs of both old log and new log are now identical.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With