同时为现有对象添加属性

Add attributes to existing object at same time

本文关键字:对象 添加 属性      更新时间:2023-09-26

假设我有这样一个简单的对象:

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';
.......

但是我想同时添加几个属性。有方便的功能吗?由于

使用ES6(这将覆盖现有的属性):

Object.assign(User, { /* some new props */ });

使用lodash(这不会覆盖现有的属性):

_.extend(User, { /* some new props */ });

在ES5中通过向User:

添加一个方法
User.add = function(newProps) {
  Object.keys(newProps).forEach(function(prop) {
    this[prop] = newProps[prop];
  }.bind(this));
};

真的,如果你想遵循OO的"原则",add方法应该放在User.prototype中。

一个解决方案:

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>