这是一个包含字符串列表的对象(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") 发送“删除”指令时,它应该以销毁“返回”运算符给出的列表中包含的字符串结束,不与变量中包含的字符串一起销毁gettersDictionnary
。但确实如此。
然后我问为什么在这种情况下“return”运算符似乎给出了对变量的引用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"