自动创建属性不起作用
Auto create property doesn't work
我期待看到:
设置
得到
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
来自哪里,所以我也为这个例子做了这些修复)。
相关文章:
- JQuery示例不起作用-“;对象没有't支持属性或方法'按钮'&”;
- margin-left和width属性在mozillafirefox中不起作用
- 未捕获的类型错误:无法设置属性'innerHTML'如果为null,则将脚本移动到正文不会;不起作用
- 在jQuery中链接时CSS属性不起作用
- 使用WebView中的javascript触发setVisibility属性;不起作用
- .split() 数据属性在应该工作的时候不起作用
- 函数中的 angularJS 访问对象属性不起作用
- 当我关联runat=“server”属性时,JQuery UI 按钮集在单选按钮上不起作用
- 属性选择器不起作用(语法错误、无法识别的表达式)
- 使用 Div 标签的 location.href 属性时,Eval 不起作用
- 当图像和链接是 json 对象属性的值时,它们不起作用
- 为什么 HTML 中的 Value 属性在与 AngularJS 中的 ng-model 一起使用时不起作用
- JQuery多属性筛选器不起作用
- 占位符属性嵌入IE中的iframe时不起作用
- 使用 css() 更改自定义属性不起作用
- $(this) 在 onclick 属性中不起作用
- 调用类属性不起作用
- 标签的属性在角度方向上不起作用
- 为什么onclick属性不起作用
- jQuery代码不起作用(属性不是函数)