2015-05-28 72 views
16

我想用Object.assign做一些非常簡單的事情。ES5 Object.assign等效

var firstObj = {name : "Saba H.", rollNo : 1}; 
var secondObj = {college : "WCE"}; 
var wholeObj = Object.assign(firstObj, secondObj); 

console.log(wholeObj); // {name : "Saba H.", rollNo : 1, college : "WCE"} 

由於Object.assign是ECMAScript6和諧議案的一部分,在許多瀏覽器不支持,是有可能做的ES5?如果沒有,那麼是否有任何微型庫?

+2

https://lodash.com/docs#assign基於非常相同 - 基於編輯,看看在lodash源代碼,爲什麼不呢? –

+2

在[mdn](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)中可以看到polyfill – Grundy

回答

21

在你可以使用像underscore.js,

_.extend(firstObj, secondObj); 

在jQuery中,你可以使用,

$.extend({},firstObj,secondObj); 

在純javascipt的,您可以使用此功能合併n數目:

function mergeObjects() { 
    var resObj = {}; 
    for(var i=0; i < arguments.length; i += 1) { 
     var obj = arguments[i], 
      keys = Object.keys(obj); 
     for(var j=0; j < keys.length; j += 1) { 
      resObj[keys[j]] = obj[keys[j]]; 
     } 
    } 
    return resObj; 
} 
0

我在Object.assign上發現了一個可用的polyfill MDN(真棒,謝謝!):

if (typeof Object.assign != 'function') { 
    // Must be writable: true, enumerable: false, configurable: true 
    Object.defineProperty(Object, "assign", { 
    value: function assign(target, varArgs) { // .length of function is 2 
     'use strict'; 
     if (target == null) { // TypeError if undefined or null 
     throw new TypeError('Cannot convert undefined or null to object'); 
     } 

     var to = Object(target); 

     for (var index = 1; index < arguments.length; index++) { 
     var nextSource = arguments[index]; 

     if (nextSource != null) { // Skip over if undefined or null 
      for (var nextKey in nextSource) { 
      // Avoid bugs when hasOwnProperty is shadowed 
      if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) { 
       to[nextKey] = nextSource[nextKey]; 
      } 
      } 
     } 
     } 
     return to; 
    }, 
    writable: true, 
    configurable: true 
    }); 
}