2013-06-20 106 views
0

我期待看到:
设置自动创建属性不起作用

获取

可有人请向我解释为什么这个代码不工作?感谢

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); 
+0

什么是叠加? – Nemoy

回答

0

嗯,首先,是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来源,所以我做了例如那些修复以及)。