I'm using sinon.js for testing, but it's not relevant here. Original sinon implementation contains following code:
sinon = {
log: function() {}
//...
}
there is just a stub log
function to be overriden by users, higher-level sinon functions use that. That makes sense. And now I try to define sinon.log function for myself:
sinon.log = console.log;
When I try to log something, I get a nasty error I don;t clearly understand:
sinon.log(1)
> TypeError: Illegal invocation
I have found that it has something to do with the this
context in javascript, because when I change this implementation to:
sinon.log = function(){ console.log.apply(console, arguments) };
it works perfectly for n arguments (just as console.log does). But I don't know why should I set the this
object to console object. Does it rely on internal browser implementation (I'm using chrome)? Is there any standard for that, e.g. I should always set this
object to console in such case?
I ask for the explanation: how do the internals work, why is this error raised and why is my second implementation correct.