gpt4 book ai didi

javascript - getter 方法提供意外的引用

转载 作者:行者123 更新时间:2023-11-28 00:04:07 25 4
gpt4 key购买 nike

这是一个对象包含字符串列表(valuesDictionnary),这些字符串可以从外部读取对象的 getter 列表设置为对象的属性(gettersDictionnary)。

这个奇怪的结构被用来制作字符串列表不可从外部配置,但可配置,因此可从外部删除里面。

var obj = new (function () {

var gettersDictionnary = {},
valuesDictionnary = {
anyValue: "problem"
};

Object.defineProperty(this, "gettersDictionnary", {
configurable: false,
get: function () {
return gettersDictionnary;
}
});

Object.defineProperty(gettersDictionnary, "anyValue", {
configurable: true,
get: function () {
return valuesDictionnary["anyValue"];
}
});

})();

重点是,当“删除”指令发送到 getter 之一时(“anyValue”)从物体的外部来看,它应该以破坏告终由“return”运算符给出的列表中包含的字符串,而不是变量 gettersDictionnary 中包含的字符串被破坏。但确实如此。

然后我问为什么在这种情况下“返回”运算符似乎给出对变量 gettersDictionnary 的引用,但不是它的值应该可以。

console.log(obj.gettersDictionnary.anyValue); //"problem"

delete obj.gettersDictionnary.anyValue;

console.log(obj.gettersDictionnary.anyValue); //"undefined"

最后一个 console.log 应该给出“问题”,为什么没有?

这是完整的代码片段:

var obj = new (function () {

var gettersDictionnary = {},
valuesDictionnary = {
anyValue: "problem"
};

Object.defineProperty(this, "gettersDictionnary", {
configurable: false,
get: function () {
return gettersDictionnary;
}
});

Object.defineProperty(gettersDictionnary, "anyValue", {
configurable: true,
get: function () {
return valuesDictionnary["anyValue"];
}
});

})();

console.log(obj.gettersDictionnary.anyValue); //"problem"

delete obj.gettersDictionnary.anyValue;

console.log(obj.gettersDictionnary.anyValue); //"undefined"

最佳答案

以下是 Ecmascript 规范中的 delete 运算符的语义:

When the [[Delete]] internal method of O is called with property name P and the Boolean flag Throw, the following steps are taken:

  1. Let desc be the result of calling the [[GetOwnProperty]] internal method of O with property name P.
  2. If desc is undefined, then return true.
  3. If desc.[[Configurable]] is true, then
    1. Remove the own property with name P from O.
    2. Return true.
  4. Else if Throw, then throw a TypeError exception.
  5. Return false.

如您所见,解决方案是使该属性不可可配置

关于javascript - getter 方法提供意外的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31505481/

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