因此,这在firefox和opera中是可行的,但在chrome或IE中则不然。
window.onload=function(){
IMS=new Object();
IMS.putLog=console.log;
IMS.putLog('IMS Initialized...');
IMS.putLog('Loading...');
loadData(userName, passWord);
IMS.putLog('Loaded...');
};
不合法调用失败
不知道为什么?有什么建议吗?
发布于 2014-02-27 22:14:26
原因是当您调用IMS.putLog
时,函数的this
变量是IMS
;console.log
实现可能依赖于this
是console
。
这里有一个解决办法:
IMS.putLog = console.log.bind(console);
这将确保在调用日志函数时this
是console
。
不幸的是,这不适用于IE < 9,或者其他浏览器。我知道bind
不适用于PhantomJS,如果这很重要的话。
发布于 2014-02-27 22:15:37
参见:"Uncaught TypeError: Illegal invocation" in Chrome
基本上,当您重新分配console.log时,它会更改范围。我猜它在火狐和Opera中很管用,只是运气好。
更好的解决办法是:
IMS.putLog = function(){
console.log.apply(console, arguments); //any passed to IMS.putLog will get passed to console.log
};
同样的结果,只是在正确的范围内调用。
编辑:这应该适用于所有支持console.log Edit2: Brainfart -参数的浏览器。
https://stackoverflow.com/questions/22081618
复制相似问题