gpt4 book ai didi

javascript - 如何处理 PhantomJS 中的 `console.log.bind(console)` 抛出错误?

转载 作者:行者123 更新时间:2023-11-29 10:37:48 24 4
gpt4 key购买 nike

使用 PhantomJS 1.9.x,我想在我的代码中使用 console.log.bind(console),但由于 console.log.bind 而引发错误> undefined(与 console.error.bind(console) 等相同)

PhantomJS 1.x 的一个已知问题是它不支持 Function.prototype.bind

然而,即使在包含 bind polyfill 之后事情没有按预期工作:

 console.log(Function.prototype.bind);
// function bind(obj) { ... }
console.log(console.log.bind);
// undefined

我该如何解决这个问题?

最佳答案

在 PhantomJS 中,console 似乎有点特殊,它不是 Function 的实例(与 Chrome 或 Firefox 相反)。因此扩展 Function.prototype 对它没有任何作用。

console.log(typeof console.log === "function");
// true
console.log(console.log instanceof Function);
// false

(可能 console.log 来自不同的 JavaScript 上下文,这里的问题与 myArray instanceof Array 评估为 falsemyArray 来自 iframe 时)。

要解决此问题,除了为 Function.prototype.bind 包含一个 polyfill 之外,您还可以手动将 bind 分配给 console 方法,像这样:

if (!console.log.bind) {
// PhantomJS quirk
console.log.constructor.prototype.bind = Function.prototype.bind;
}

在此之后,所有控制台方法都将具有 .bind():

console.log(console.log.bind);   // function bind(obj) { ... }
console.log(console.info.bind); // function bind(obj) { ... }
console.log(console.debug.bind); // function bind(obj) { ... }
console.log(console.warn.bind); // function bind(obj) { ... }
console.log(console.error.bind); // function bind(obj) { ... }

关于javascript - 如何处理 PhantomJS 中的 `console.log.bind(console)` 抛出错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34046318/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com