I want to create my own version of console.log, using a 'curry' function and including the possibility to show or not the logs. ( inspired for SecretsOfTheJavascriptNinja )
So I implemented this function using closures:
Function.prototype.conditionalCurry = function() {
var fn = this;
var args = Array.prototype.slice.call(arguments);
var show = args[0];
args = args.slice(1, args.length);
return function() {
if (show) {
return fn.apply(this, args.concat(
Array.prototype.slice.call(arguments)));
}
else return;
};
};
When I tested the code using node in the terminal it works:
var newLog = console.log.conditionalCurry(true, 'Always visible|' );
newLog('log visible'); // gives on the console: Always visible| log visible
newLog = console.log.conditionalCurry(false, 'never visible|' );
newLog('log visible'); // gives nothing, it works!
But when I test the code on Chrome 48.0.2564.109 and in firefox 44.0.2 arises a problem, and I think is the same in both cases.
As far as I can see, somehow the context 'this' passed to the function conditionalCurry when I use node in terminal, is an anonymous function, but in the case of the browsers 'this' appear as a function called 'log', and I believe this is breaking the code.
Any idea how can I implement this functionality in browsers?
Fiddle
Thanks in advance!!!
With Bergi's solution, now it works: Fiddle
I would be weary about modifying the prototype of existing language features such as Function. It seems you really want instances of these logging tools back, so you may as well define that instance and use it in the sort of "classical" sense.
For example, let's create a "class" (just to use the language agnostic term) called "Logger". Instances of logger will be able to be configurable to show a prefixed message, conditionally send messages to the log, and also use the log in a semi traditional manner.
function Logger(display,prefix){
this.display = display == [][0] ? true : display;
this.prefix = prefix;
}
Logger.prototype.log = function(){
if(this.display){
[].splice.apply(arguments,[0,0,this.prefix])
console.log.apply(console,arguments);
}else{
console.log(this.prefix);
}
return this;
};
Logger.prototype.show = function(truthy){
this.display = !!truthy;
return this;
};
Logger.prototype.note = function(msg){
this.prefix = msg;
return this;
};
var newLog = new Logger(true,'always |');
newLog.log('show me');//always | show me
newLog.note('never show').show(false);
newLog.log('show me now');//never show
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