gpt4 book ai didi

javascript - 原型(prototype)上具有默认属性的 es6 类会抛出 Traceur

转载 作者:行者123 更新时间:2023-12-02 16:29:59 24 4
gpt4 key购买 nike

我最近开始使用 Traceur,并在原型(prototype)上创建具有默认值的类时偶然发现了一个奇怪的行为。我想知道这是否是 Traceur 中的错误,或者这是 ES6 类的预期行为?

class hasDefault {
setValue ( v ) {
this.v = v;
}
}
Object.defineProperty( hasDefault.prototype, "v", {
value : 5,
enumerable : true
});

let a = new hasDefault;
console.assert(a.v === 5);
a.setValue(2);
console.assert(a.v === 2);

run in traceur REPL

当我尝试设置它时,它会抛出一个错误,无法将其分配给只读属性“v”。这是没有意义的,因为属性是在原型(prototype)上定义的,而不是在实例上定义的。另外,我无法在密封/卡住/不可扩展的对象上抛出 es5 中的错误,据我所知,V8 中没有实现代理,所以...它首先是如何抛出错误的?这不是编译时错误。

我的主要兴趣不是“让它发挥作用”,这是微不足道的。您所需要做的就是将 this.v = v 替换为 Object.defineProperty 等效项。我主要想知道它是否以及为什么会以这种方式运行,以及此数据结构中是否存在负面性能影响,这些负面影响超过了通过将默认属性分配给原型(prototype)而不是将它们存储在每个实例上所获得的内存增益。

最佳答案

It throws an error that I can't assign to the read only property "v" when I try to set it. Which doesn't make sense as the property is defined on the prototype, not the instance.

是的,该属性是只读的,因为 writable 属性默认为 false。当v属性被继承时,该属性对于赋值也有效。

Also I'm unable to get that Error to throw in es5

您只需使用严格模式即可:

"use strict";
var test = Object.create(Object.defineProperty({}, "v", {value: 5, enumerable: true}));
console.log(test.v) // 5
test.v = 1; // Unhandled Error: Invalid assignment in strict mode

关于javascript - 原型(prototype)上具有默认属性的 es6 类会抛出 Traceur,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28391290/

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