gpt4 book ai didi

javascript - 为什么在 Firefox 中 Function.prototype.func=... 不影响 console.log?

转载 作者:数据小太阳 更新时间:2023-10-29 05:33:47 26 4
gpt4 key购买 nike

我已经使用 Function.prototype.func = ... 添加了一个函数到 Function 但在 Firefox 中它没有被添加 console.log:

Function.prototype.func = function () { return this.toString(); };
alert(typeof console.log.func); // in FF: undefined, in Chrome: function

这是错误还是有任何原因?

最佳答案

在 Firefox 中很明显:

var foo = function() {}
foo.__proto__ == Function.prototype;

true,而语句:

console.log.__proto__ == Function.prototype;
console.log instanceof Function;

都是false

因此,console.log 的原型(prototype)链中不包含 Function.prototype,因此更改 Function.prototype控制台日志。这很好,因为 console 是一个 host object (而不是 ECMAScript 规范中的 native 对象)并且可以按照 Mozilla(或 Google、Microsoft 等)的意愿行事。

为什么存在这种行为?我不是 Firefox 开发人员,所以我不能肯定地说,但我最好的猜测是,这是专门完成的,因为 console 是一个调试工具。如果您在 Function 的原型(prototype)链上乱搞,然后想使用 console.log 来验证您在做什么,那么如果您的调试报告工具 < em>自己 开始搞砸并向您误报事情。

编辑:

console 函数有一个单独的原型(prototype)链供所有函数使用:

console.log.__proto__ == console.dir.__proto__ // true
console.log.__proto__.func = 5;
console.dir.__proto__.func == 5 // true

关于javascript - 为什么在 Firefox 中 Function.prototype.func=... 不影响 console.log?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16364006/

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