gpt4 book ai didi

javascript - 这个对象在 Chrome 中出现错误 'message' getter

转载 作者:行者123 更新时间:2023-11-29 22:08:49 25 4
gpt4 key购买 nike

对于这段代码,我在 Chrome 与 Firefox 和 Safari 中看到了不同的行为:

var FancyError = function(x) { this.x = x; };
FancyError.prototype = new Error;

Object.defineProperties(FancyError.prototype, {
'message': {
'get': function(){ return "fancy:" + this.x; }
}
});

new FancyError("hi") + '';

严格模式下不会产生错误。该错误是由于 chrome 使用与预期不同的 this 对象调用消息 getter 引起的。

Firefox/Safari 输出:"Error: fancy:hi"

Chrome 输出:"Error: fancy:undefined"

知道这里发生了什么吗?

测试版本

Chrome:30.0.1599.69 OSX

火狐:24 OSX

Safari :6.0.5 OSX

最佳答案

这显然是 Chrome 的 Error.prototype.toString 中的错误:

var FancyError = function(x) { this.x = x; };
FancyError.prototype = new Error;
FancyError.prototype.x = "I'm the prototype";

Object.defineProperties(FancyError.prototype, {
'message': {
'get': function(){ return "fancy:" + this.x; }
}
});

var fe = new FancyError("I'm the instance");

在 Chrome 中使用此设置:

  • fe.message 生成 fancy:I'm the instance
  • fe.toString() 产生 Error: fancy:I'm the prototype

第一种情况下发生的事情很容易理解:

  1. fe.message 使用参数 "message" 提示调用 [[Get]] on fe >
  2. [[Get]] 第 1 步获取在 fe 的原型(prototype)上设置的访问器描述符(因为 fe 没有它自己的消息 属性)。
  3. [[Get]] 第 6 步调用访问器描述符上的 getter,将 this 设置为调用 原始对象>[[Get]](此处为 fe 对象)。

第二种情况很奇怪。 fe.toString() 似乎在 Error 上为 "message" 执行了 [[Get]] fe 原型(prototype)中的实例。这似乎是错误的,因为 Error.prototype.toString 的第 5 步指定从 toString 中的 this 值获取 message 函数。

编辑

我之前假设问题是由 fe 的原型(prototype)链中有 Error 引起的。但是,请考虑这种情况:

var FancyError = function(x) { this.x = x; };
FancyError.prototype.x = "I'm the prototype";

Object.defineProperties(FancyError.prototype, {
'message': {
'get': function(){ return "fancy:" + this.x; }
}
});

fe = new FancyError("I'm the instance");

在这种情况下:

  • fe.messagefancy:I'm the instance as above
  • Error.prototype.toString.call(fe)Error: fancy:I'm the prototype

因此,我们必须得出结论,Chrome的Error.prototype.toString错误地使用了包含getter的原型(prototype)作为getterthis值>,这似乎与 [[Get]] 和/或 Error.prototype.toString 的第 5 步的正常行为相矛盾。

关于javascript - 这个对象在 Chrome 中出现错误 'message' getter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19302937/

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