简体   繁体   English

javascript将console.log分配给对象

[英]javascript assign console.log to an object

I'm using sinon.js for testing, but it's not relevant here. 我正在使用sinon.js进行测试,但这与此处无关。 Original sinon implementation contains following code: 原始的sinon实现包含以下代码:

sinon = {
  log: function() {}
  //...
}

there is just a stub log function to be overriden by users, higher-level sinon functions use that. 用户只有一个存根log功能可以覆盖它,更高级的sinon函数使用它。 That makes sense. 那讲得通。 And now I try to define sinon.log function for myself: 现在,我尝试为自己定义sinon.log函数:

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: 我发现它与javascript中的this上下文有关,因为当我将此实现更改为:

sinon.log = function(){ console.log.apply(console, arguments) };

it works perfectly for n arguments (just as console.log does). 它非常适合n个参数(就像console.log一样)。 But I don't know why should I set the this object to console object. 但是我不知道为什么要this对象设置为控制台对象。 Does it rely on internal browser implementation (I'm using chrome)? 它是否依赖于内部浏览器实现(我正在使用chrome)? Is there any standard for that, eg I should always set this object to console in such case? 是否有任何标准,例如在这种情况下我应该始终this对象设置为控制台?

I ask for the explanation: how do the internals work, why is this error raised and why is my second implementation correct. 我要求解释:内部结构如何工作,为什么会引发此错误,为什么我的第二个实现是正确的?

This works for me in a jsfiddle: 这在jsfiddle中为我工作:

sinon.log = console.log.bind(console)

(jsfiddle: http://jsfiddle.net/vjotqjka/ ) (jsfiddle: http : //jsfiddle.net/vjotqjka/

console.log has a wierd behaviour with its this, which is why I used console.log.bind(console) to keep its this set to console. console.log与此有一个怪异的行为,这就是为什么我使用console.log.bind(console)将其设置为console的原因。 The behaviour of console.log with its this is not browser specific and is working as intended. console.log的行为及其与浏览器无关,并且按预期工作。 This stackoverflow answer looks related: TypeError: Illegal Invocation on console.log.apply 这个stackoverflow答案看起来很相关: TypeError:console.log.apply上的非法调用

More information about function.prototype.bind can be found here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind 有关function.prototype.bind的更多信息,可以在这里找到: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM