一、概述
我们先看看ES6官方文档是怎么介绍的?
Object.assign()
方法用于将所有可枚举属性的值从一个或多个源对象复制到目标对象。它将返回目标对象。简单来说,就是
Object.assign()
是对象的静态方法,可以用来复制对象的可枚举属性到目标对象,利用这个特性可以实现对象属性的合并。
二、用法
Object.assign(target, ...sources)
参数: target--->目标对象
source--->源对象
返回值:target,即目标对象
三、使用示例
1、目标对象和源对象无重名属性
var target={name:'guxin',age:18};
var source={state:'single'}
var result=Object.assign(target,source);
console.log(target,target==result);
结果:
{name: 'guxin', age: 18, state: 'single'} true
var result=Object.assign({},target,source);
2、目标对象和源对象有重名属性
如果有同名属性的话,后面的属性值会覆盖前面的属性值。
var target={name:'guxin',age:18}
var source={state:'signle',age:22}
var result=Object.assign(target,source)
console.log(target)
运行结果:
{name: 'guxin', age: 22, state: 'signle'}
3、有多个源对象
有多个源对象情况也是和一个源对象一样的。
没有同名的属性会直接复制到目标对象上,同名的属性后面的属性值会覆盖前面的同名属性值。
var target={name:'guxin',age:18}
var source1={state:'signle',age:22}
var source2={mood:'happy',age:25}
var result=Object.assign(target,source1,source2)
console.log(target)
运行结果:
{name: 'guxin', age: 25, state: 'signle', mood: 'happy'}
四、注意事项:
-
Object.assign
方法只会拷贝源对象自身的并且可枚举的属性到目标对象,继承属性和不可枚举属性是不能拷贝的。 -
针对深拷贝,需要使用其他办法,因为
Object.assign()
拷贝的是属性值。假如源对象的属性值是一个对象的引用,那么它也只指向那个引用。 -
目标对象自身也会改变
-
异常会打断后续拷贝任务
五、兼容性
目前IE浏览器不兼容Object.assign(),如果需要兼容IE的话最好不要直接使用这个方法。
解决方法如下:
1、添加方法
使用以下方式进行添加
if(typeof Object.assign != 'function') {
(function() {
Object.assign = function(target) {
'use strict';
if(target === undefined || target === null) {
throw new TypeError('Cannot convert undefined or null to object');
}
var output = Object(target);
for(var index = 1; index < arguments.length; index++) {
var source = arguments[index];
if(source !== undefined && source !== null) {
for(var nextKey in source) {
if(source.hasOwnProperty(nextKey)) {
output[nextKey] = source[nextKey];
}
}
}
}
return output;
};
})();
}
2、替换方法
使用 $.extend()
替换 Object.assign()
。
六、与$.extend()的比较
1、相同点
- 函数用于将一个或多个对象的内容合并到目标对象。
- 都可以用于浅拷贝
$.extend(target ,defaults, options) 与Object.assign(target ,defaults, options)
2、不同点
$.extend(true, target ,defaults, options)
可用于深拷贝。
$.extend(true,{},a,b)
- true:是否深度拷贝,不加为false,浅拷贝,加了深拷贝
- {}:将合并结果保存到新对象,这样原对象将不会发生改变
- a:第一个合并的对象
- b:第二个合并的对象