【发布时间】:2015-11-01 19:07:57
【问题描述】:
以下 sn-p 在 Firefox 中运行时会在 Chrome(和 Safari)中产生错误。
我希望在 javascript 控制台中显示 2 个数字,但在 Chrome 中我只得到第一个,然后是 Uncaught TypeError: Illegal invocation
// a generic promise that return a random float
var makePromise = function() {
return $.Deferred().resolve(Math.random());
}
// This works in all browsers
makePromise().then(function(d) {
console.log(d);
});
// This works in firefox only
makePromise().then(console.log);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
为什么会这样?
旁注:我的问题与this question不同。
更新
感谢 cmets 并回答使用console.log 作为需要做的回调
makePromise().then(console.log.bind(console));
【问题讨论】:
-
可能是一些 webkit 安全限制。
-
console.log.bind(console)。没有什么能保证它是一个“静态”函数。 -
正如@zerkms 所说,
console.log.bind(console)。令人惊奇的是console.log应该在 FF 中工作。
标签: javascript function google-chrome firefox jquery-deferred