让我说我有这个简单的对象:
var User = {
name: 'Hans',
get_name: function(){return this.name},
street: 'Kings',
postcode: '482932',
city: 'New York'
}
为了更好地概述,我想做这样的事情:
var User = {
name: 'Hans',
get_name: function(){return this.name},
};
//Adress Information
User.add({
street: 'Kings',
postcode: '482932',
city: 'New York'
});
正如所料,这不起作用。为了实现类似的东西我可以写:
User.street = 'Kings';
User.postcode = '482932';
.......
但我想同时添加几个属性。它有一个方便的功能吗?感谢
答案 0 :(得分:1)
使用ES6(这将覆盖现有属性):
Object.assign(User, { /* some new props */ });
使用lodash(这不会覆盖现有属性):
_.extend(User, { /* some new props */ });
在ES5中向用户添加方法:
User.add = function(newProps) {
Object.keys(newProps).forEach(function(prop) {
this[prop] = newProps[prop];
}.bind(this));
};
实际上,add
方法应该放在User.prototype
中,如果您想遵循OO"原则"。
答案 1 :(得分:1)
一个解决方案:
var User = {
name: 'Hans',
get_name: function(){return this.name},
};
User.add = function(obj){
var me = this;
Object.keys(obj).forEach(function(o){
if(! me[o] ) me[o] = obj[o];
})
}
//Adress Information
User.add({
street: 'Kings',
postcode: '482932',
city: 'New York'
});
console.dir(User)
/*
name "Hans"
get_name function()
add function(obj)
street "Kings"
postcode "482932"
city "New York"
*/
var User = {
name: 'Hans',
get_name: function(){return this.name},
};
User.add = function(obj){
var me = this;
Object.keys(obj).forEach(function(o){
if(! me[o] ) me[o] = obj[o];
})
return this;
}
//Adress Information
User.add({
street: 'Kings',
postcode: '482932',
city: 'New York'
});
console.dir(User);
/*
name "Hans"
get_name function()
add function(obj)
street "Kings"
postcode "482932"
city "New York"
*/
document.getElementById('el').innerHTML = '<pre>'+JSON.stringify(User , null , ' ')+'</pre>';
<div id='el'><div>