Javascript 如果只知道属性名,可以通过setter和getter从对象的列表中定义属性吗?
我有以下代码:Javascript 如果只知道属性名,可以通过setter和getter从对象的列表中定义属性吗?,javascript,Javascript,我有以下代码: var properties = ["name", "sex", "location"]; o={}; for (var i=0, l=properties.length; i<l; i++) { Object.defineProperty(o, properties[i],{ get: function () {return "hello";}, set: function(val){ console.log
var properties = ["name", "sex", "location"];
o={};
for (var i=0, l=properties.length; i<l; i++) {
Object.defineProperty(o, properties[i],{
get: function () {return "hello";},
set: function(val){
console.log(properties[i] + ' is being set');
},
enumerable: true,
configurable: true
});
}
o.name = "something";
console.log(o.name);
在集合函数的主体中
name = val;
这样代码就可以工作了。
如果我写了这样的东西
this[properties[i]] = val;
或
我最终进入了一个无限循环,我的问题是我只有一个字符串形式的属性名。评估是唯一的解决方案吗
你们中有人知道这件事是否可行吗。我以前做过一些研究,但找不到任何解决办法
先谢谢你
我在这里用一些东西来完成我的问题,因为有人写了:
你要做的是动作属性。无法为这些操作属性设置任何值。因此,您需要创建另一个数据属性来保存相应的数据。e、 g-
var properties = ["name", "sex", "location"];
o={};
for (var i=0, l=properties.length; i<l; i++) {
Object.defineProperty(o, properties[i],{
get: function () {return this["_"+properties[i]];},
set: function(val){
this["_"+properties[i]] = val;
},
enumerable: true,
configurable: true
});
}
o.name = "something";
console.log(o.name);
我知道我可以使用其他属性来保存这些值,但我希望我的代码运行时,就像我可以逐个定义它们一样,而不必将这些值存储在其他属性/变量中,对我来说,我可以一个接一个地定义它们,而且它是有效的,当我试图动态地定义它们时,如果闭包中没有额外的属性/变量,我就不能:
Object.defineProperty(o, "name",{
get: function () {return name;},
set: function(val){
name = val;
},
enumerable: true,
configurable: true
});
Object.defineProperty(o, "sex",{
get: function () {return sex;},
set: function(val){
sex = val;
},
enumerable: true,
configurable: true
});
Object.defineProperty(o, "location",{
get: function () {return location;},
set: function(val){
location = val;
},
enumerable: true,
configurable: true
});
好了,伙计们,姑娘们,我终于明白发生了什么。变量名,性别和位置,正如我在1×1定义中使用的,是在window对象上定义的可变位置属性,这是代码工作的唯一原因。我现在清楚地意识到,我必须分配内存将值存储在其他地方,因为你们都向我解释,在其他地方它根本不工作,imho的最佳位置是在闭包中,以便值是私有的。我花了一些时间才明白,当您使用setter函数和getter函数来保存该值时,javascript没有任何内部valueplace属性只是绑定到您设置的访问器或描述符对象,并将其用于进一步的计算
谢谢大家。您要做的是action属性。无法为这些操作属性设置任何值。因此,您需要创建另一个数据属性来保存相应的数据。e、 g-
var properties = ["name", "sex", "location"];
o={};
for (var i=0, l=properties.length; i<l; i++) {
Object.defineProperty(o, properties[i],{
get: function () {return this["_"+properties[i]];},
set: function(val){
this["_"+properties[i]] = val;
},
enumerable: true,
configurable: true
});
}
o.name = "something";
console.log(o.name);
这样做怎么样: 变量属性=[姓名、性别、位置]; o={ 状态:{}//动态保存这些属性的值。 }; 对于变量i=0,l=properties.length;i
var properties = ["name", "sex", "location"];
o={};
for (var i=0, l=properties.length; i<l; i++) {
Object.defineProperty(o, properties[i],{
get: function () {return this["_"+properties[i]];},
set: function(val){
this["_"+properties[i]] = val;
},
enumerable: true,
configurable: true
});
}
o.name = "something";
console.log(o.name);