有没有办法同时设置对象的多个变量。例如,我有以下代码:
_p.a=1;
_p.b=2;
_p.c=3;
我想做的事情如下:
_p.[{'a': 1, 'b': 2, 'c': 3}]; // this code does not do the trick
有没有办法做类似的事情?
答案 0 :(得分:3)
您可以使用Object.defineProperties
:
var _p = {
foo: 'bar'
};
Object.defineProperties(_p, {
'a': {
value: 1,
writable: true,
enumerable: true
},
'b': {
value: 2,
writable: true,
enumerable: true
},
'c': {
value: 3,
writable: true,
enumerable: true
}
});
console.log(_p); //Object {foo: "bar", a: 1, b: 2, c: 3}
答案 1 :(得分:0)
你有一个对象_p并希望使用另一个对象来放置它 - 在你的情况下,是一个文字。
jquery有一个实用工具:
http://api.jquery.com/jQuery.extend/
$.extend(_p, {'a': 1, 'b': 2, 'c': 3});
下划线也是如此:
http://underscorejs.org/#extend
_.extend(_p, {'a': 1, 'b': 2, 'c': 3})
答案 2 :(得分:0)
我想你可以使用这样的东西:
Object.prototype.setProps = function(props){
for(var i in props){
if(props.hasOwnProperty(i))
this[i] = props[i];
}
}
使用:
_p.setProps({a: 1, b: 2, c: 3});