先上图:
$.extend()
Object.assign()
他们的结果都是复制对象到目标对象.
翻一下文档:
>>Object.assign()
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
大致描述为:
如果目标对象中的属性具有相同的键,则属性将被源中的属性覆盖。后来的源的属性将类似地覆盖早先的属性。
Object.assign
方法只会拷贝源对象自身的并且可枚举的属性到目标对象。该方法使用源对象的[[Get]]和目标对象的[[Set]],所以它会调用相关 getter 和 setter。因此,它分配属性,而不仅仅是复制或定义新的属性。如果合并源包含getter,这可能使其不适合将新属性合并到原型中。为了将属性定义(包括其可枚举性)复制到原型,应使用Object.getOwnPropertyDescriptor()和Object.defineProperty() 。String类型和 Symbol 类型的属性都会被拷贝。
在出现错误的情况下,例如,如果属性不可写,会引发TypeError,如果在引发错误之前添加了任何属性,则可以更改target对象。
注意,Object.assign 不会跳过那些值为 null 或 undefined 的源对象。
>>$.extend()
https://api.jquery.com/jQuery.extend/#jQuery-extend-target-object1-objectN
大致描述为:
Merge the contents of two or more objects together into the first object.
When two or more object arguments are supplied to $.extend(), properties from all of the objects are added to the target
object. Arguments that are null or undefined are ignored.If only one argument is supplied to $.extend(), this means the target
argument was omitted. In this case, the jQuery object itself is
assumed to be the target. By doing this, you can add new functions to
the jQuery namespace. This can be useful for plugin authors wishing to
add new methods to JQuery.Keep in mind that the target object (first argument) will be modified,
and will also be returned from $.extend(). If, however, you want to
preserve both of the original objects, you can do so by passing an
empty object as the target:
var object = $.extend({}, object1, object2);
The merge performed by $.extend() is not recursive by default; if a
property of the first object is itself an object or array, it will be
completely overwritten by a property with the same key in the second
or subsequent object. The values are not merged. This can be seen in
the example below by examining the value of banana. However, by
passing true for the first function argument, objects will be
recursively merged.Warning: Passing false for the first argument is not supported.