将对象附加到现有对象

kwa*_*wah 5 javascript

是否有任何现有方法将对象附加到另一个对象?

我已经快速将这些扔在一起,但我不确定几件事情:

  • 我正确处理方法吗?我添加了一个附加异常,但是当存在其他原型函数时呢?我应该忽略新类中的函数吗?

  • 我应该怎么做null/undefined值?

  • 另外,我刚想到数组......处理数组的最佳方法是什么?typeof报告为'对象'..我想测试Array().构造函数值将是前进的方向

除了这几个问题之外,它似乎正如我所希望的那样起作用(仅在新对象中存在的情况下覆盖/添加现有对象的各个部分).我错过了任何边缘案例吗?

Object.prototype.append = function(_newObj)
{
  if('object' !== typeof _newObj) {
    console.info("ERROR!\nObject.prototype.append = function(_newObj)\n\n_newObj is not an Object!");
  }

  for (newVar in _newObj)
  {
    switch(typeof _newObj[newVar]){
      case "string":
        //Fall-through
      case "boolean":
        //Fall-through
      case "number":
        this[newVar] = _newObj[newVar];
      break;

      case "object":
        this[newVar] = this[newVar] || {};
        this[newVar].append(_newObj[newVar]);
      break;

      case "function":
        if(newVar !== 'append'){
          this[newVar] = _newObj[newVar];
        }
      break;
    }
  }

  return this;

}


var foo = { 1:'a', 2:'b', 3:'c' };
var bar = { z: 26, y: 25, x: 24, w: { 'foo':'bar'}, v: function(){ alert('Hello world"'); } };

foo.append(bar);
console.info(foo);
Run Code Online (Sandbox Code Playgroud)

pal*_*wim 2

我喜欢。我在代码中使用了类似但不那么强大的方法。但将其实现为 Object 类的静态方法可能会更安全:

if (typeof Object.merge !== 'function') {
    Object.merge = function(_obj, _newObj)
    {
        if("object" !== typeof _obj)
            console.info("ERROR!\nObject.merge = function(_obj, _newObj)\n\n_obj is not an Object!");
        if("object" !== typeof _newObj)
            console.info("ERROR!\nObject.merge = function(_obj, _newObj)\n\n_newObj is not an Object!");

        for (newVar in _newObj)
        {
            switch(typeof _newObj[newVar]){
                case "object":
                    _obj[newVar] = _obj[newVar] || {};
                    Object.merge(_obj[newVar], _newObj[newVar]);
                    break;
                case "undefined": break;
                default: // This takes care of "string", "number", etc.
                    _obj[newVar] = _newObj[newVar];
                    break;
            }
        }
        return _obj;
    }
}

var foo = { 1:'a', 2:'b', 3:'c' };
var bar = { z: 26, y: 25, x: 24, w: { 'foo':'bar'}, v: function(){ alert('Hello world"'); } };
Object.merge(foo, bar);
console.info(foo);
Run Code Online (Sandbox Code Playgroud)

为了回答您的问题,我也没有找到任何更好的方法(在框架之外)来做到这一点。对于空/未定义值,如果有空_newObj/未定义值,那么您的收件人对象不应该也有这些值(即不要为这些值做任何特殊情况)吗?