自动创建属性不起作用

Auto create property doesn't work

本文关键字:不起作用 属性 创建      更新时间:2023-09-26

我期待看到:
设置

得到

15

谁能给我解释一下为什么这个代码不起作用?由于

var myObj = new MyObj();
function CreateSimpleProperty(propertyName) {
    Object.defineProperty(myObj, propertyName, {
        set: function (aVal) {
            this[propertyName] = aVal;
            console.log("Setting");
        },
        get: function () {
            console.log("Getting");
            return this[propertyName];
        }
    });
}
CreateSimpleProperty("TEST");
Overlay.TEST = 15;
console.log(Overlay.TEST);

首先,Overlay应该是myObj吗?假设是这样,你的代码将会在一个无限循环中结束,因为你的setter中的this[propertyName] = aVal;将会无限地为自己调用setter。您将需要以其他方式存储该值。这里,我将其保存为_TEST,如下所示。

下面是代码和一个工作的jsFiddle: http://jsfiddle.net/rgthree/3s9Kp/

var myObj = {};
function CreateSimpleProperty(propertyName) {
    Object.defineProperty(myObj, propertyName, {
        set: function (aVal) {
            this['_'+propertyName] = aVal;
            console.log("Setting");
        },
        get: function () {
            console.log("Getting");
            return this['_'+propertyName];
        }
    });
}
CreateSimpleProperty("TEST");
myObj.TEST = 15;
console.log(myObj.TEST);

(显然,我不知道你的MyObj是什么或Overlay来自哪里,所以我也为这个例子做了这些修复)。