$.extend()和Object.assign()复制对象到目标对象

先上图:

$.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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值