本机警报的函数引用失败,调用对象无效

时间:2015-08-09 15:03:06

标签: javascript alert chaining

请考虑以下代码:

_x0022_ReceiptStockHNo

这将完美执行并提醒function test() { return { alert : function(txt){ alert(txt);} } } test().alert("Boo");

以下内容将失败:

Boo

错误function test() { return { alert : window.alert } } test().alert("Boo");

为什么在引用window.alert时最后一个示例失败?

1 个答案:

答案 0 :(得分:1)

window.alert期望窗口被绑定到this,当你这样调用它时,它不会被满足。 (即test().alertthis设置为test()返回的对象。)

你可以这样解决:

return {
  alert : window.alert.bind(window)
}
例如,

console.log的行为方式相同。