說我有一個這樣的對象實例:Object.defineProperty得到集中返回錯誤值
var objectA = {"a": 1, "b": 2, "c" : 3};
,並在我的代碼訪問屬性是這樣的:
cc.log(objectA.a); // output 1
現在我要添加一個get/set爲這個對象提供一些簡單的加密/解密功能:
hookSetGet: function (someObject) {
for (var key in someObject) {
cc.log("key: " + key);
// store the origin value before Object.defineProperty
var pureValue = someObject[key];
// add a property to store the encrypted value
var hiddenValueKey = "__" + key;
someObject[hiddenValueKey] = undefined;
Object.defineProperty (
someObject,
key,
{
set: function (val) {
// simulate encrypt
this.hiddenValueKey = val + 1;
cc.log("hooked set: " + val + " - " + this.hiddenValueKey);
},
get: function() {
cc.log("hooked get: " + this.hiddenValueKey + " - " + (this.hiddenValueKey - 1));
// simulate decrypt
return this.hiddenValueKey - 1;
}
}
);
// trigger set to encrypt
someObject[key] = pureValue;
}
}
但是當我測試這樣的函數時:
var objectA = {"a": 1, "b": 2, "c" : 3};
this.hookSetGet(objectA);
cc.log(objectA.a);
cc.log(objectA.b);
cc.log(objectA.c);
我沒有得到的結果,我想:
key: a
hooked set: 1 - 2
key: b
hooked set: 2 - 3
key: c
hooked set: 3 - 4
hooked get: 4 - 3
3
hooked get: 4 - 3
3
hooked get: 4 - 3
3
看起來甚至當我打電話
objectA.a
我會得到的
objectA.c
值這個問題似乎很簡單,但我不能無花果排除哪裏出錯。
任何建議將讚賞,感謝:)
UPDATE:
我試着下面的代碼,而無需改變hookSetGet的代碼:
cc.log(objectA.__a);
cc.log(objectA.__b);
cc.log(objectA.__c);
,並得到:
undefined
undefined
undefined
然後我改變了hookSetGet函數:
set: function (val) {
// simulate encrypt
someObject[hiddenValueKey] = val + 1;
cc.log("hooked set: " + val + " - " + someObject[hiddenValueKey]);
},
get: function() {
cc.log("hooked get: " + someObject[hiddenValueKey] + " - " + (someObject[hiddenValueKey] - 1));
// simulate decrypt
return someObject[hiddenValueKey] - 1;
}
我將所有this.hiddenValueKey都改爲someObject [hiddenValueKey]。
,輸出是:
cc.log(objectA.__a); // 2 good
cc.log(objectA.__b); // 3 good
cc.log(objectA.__c); // 4 good
cc.log(objectA.a); // hooked get: 4 - 3 still wrong
cc.log(objectA.b); // hooked get: 4 - 3 still wrong
cc.log(objectA.c); // hooked get: 4 - 3 still wrong
是否明智,而你是列舉了它來修改一個對象? –
@MatthewHerbst:是的,這應該不重要,屬性永遠不會迭代兩次。 – Bergi
[點符號與括號表示法]的可能重複(https://stackoverflow.com/questions/4968406/javascript-property-access-dot-notation-vs-brackets)和[JavaScript閉環內循環](http:// stackoverflow.com/q/750486/1048572) – Bergi