一、相同点:
- 函数用于将一个或多个对象的内容合并到目标对象。
- 都可以用于浅拷贝
$.extend(target ,defaults, options) 与Object.assign(target ,defaults, options)
浅拷贝:
1、$.extend(target ,defaults, options):
1.1、对浅层属性:
var object1 = {
apple: 0,
banana: {weight: {test:1}, price: 100},
cherry: 97
};
var b = $.extend({},object1)
object1.apple = 2;
console.log(b)
var object1 = {
apple: 0,
banana: {weight: {test:1}, price: 100},
cherry: 97
};
var b = $.extend({},object1)
object1.banana.weight.test = 2;
console.log(b)
2.Object.assign(target ,defaults, options)
2.1对浅层属性:
var object1 = {
apple: 0,
banana: {weight: {test:1}, price: 100},
cherry: 97
};
var b = Object.assign({},object1)
object1.apple = 2;
console.log(b)
对object1内部浅层属性apple的修改对b没有影响。
2.2、对深层属性
var object1 = {
apple: 0,
banana: {weight: {test:1}, price: 100},
cherry: 97
};
var b = Object.assign({},object1)
object1.banana.weight.test = 2;
console.log(b)
对object1内部深层属性test的修改对b有影响。
二、不同点:
$.extend(true, target ,defaults, options) 可用于深拷贝
$.extend(true,{},a,b)
true:是否深度拷贝,不加为false,浅拷贝,加了深拷贝
{}:将合并结果保存到新对象,这样原对象将不会发生改变
a:第一个合并的对象
b:第二个合并的对象
深拷贝:
var object1 = {
apple: 0,
banana: {weight: {test:1}, price: 100},
cherry: 97
};
var b = $.extend(true,{},object1)
object1.banana.weight.test = 2;
console.log(b)
对object1内部深层属性test的修改对b没有影响;
- Object.assign()方法用于将所有可枚举属性的值从一个或多个源对象复制到目标对象。它将返回目标对象
Object.assign(targetobj, sources1, source2)
总结:Object.assign()对1级属性的拷贝属于神拷贝,对2级对象的拷贝属于浅拷贝。如果要使用深拷贝。可以借助loadsh中的cloneDeep()方法https://www.lodashjs.com/docs/lodash.cloneDeep