I would like to override console.log and call it on my new function.
I try something like this but I get Uncaught TypeError: Illegal invocation
:
console.log = function() {
this.apply(window, arguments);
}.bind(console.log);
console.log('as');
This is my goal:
console.error(exception);
should do:
console.error = function() {
if (typeof exception.stack !== 'undefined') {
console.error(exception.stack);
} else {
console.error.apply(windows, arguments);
}
}.bind(console.error);
console.error('as');
console.error({stack: 'my stack....'});
EDIT: Actually, it works in firefox and not in Chrome... It's a bug in Chrome: https://code.google.com/p/chromium/issues/detail?id=167911
log. To override a console method, we just need to redefine how the method is executed. You'll need to wrap your code to prevent the access of other functions to the private (original) method.
Instead of console. log() you can also use console.info() , console. error() and console. warn() .
Another way to console. log your variables is to simply place your mouse cursor on them and then wrap them on the line below with Ctrl+Alt+W + Down or the line above with Ctrl+Alt+W + Up .
Passing a function as an argument: If the function is passed to the function console. log(), then the function will display the value of the passed function(). Output: Passing a number with message as an argument: If the number is passed to the function console.
You can have something like that:
console.error = (function() {
var error = console.error;
return function(exception) {
if (typeof exception.stack !== 'undefined') {
error.call(console, exception.stack);
} else {
error.apply(console, arguments);
}
}
})();
The best way to achieve what you want :
// define a new console
var console=(function(oldCons){
return {
log: function(text){
oldCons.log(text);
// Your code
},
info: function (text) {
oldCons.info(text);
// Your code
},
warn: function (text) {
oldCons.warn(text);
// Your code
},
error: function (text) {
oldCons.error(text);
// Your code
}
};
}(window.console));
//Then redefine the old console
window.console = console;
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