You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
if(typeofObject.assign!='function'){// Must be writable: true, enumerable: false, configurable: trueObject.defineProperty(Object,"assign",{value: functionassign(target,varArgs){// .length of function is 2'use strict';if(target==null){// TypeError if undefined or nullthrownewTypeError('Cannot convert undefined or null to object');}varto=Object(target);for(varindex=1;index<arguments.length;index++){varnextSource=arguments[index];if(nextSource!=null){// Skip over if undefined or nullfor(varnextKeyinnextSource){// Avoid bugs when hasOwnProperty is shadowedif(Object.prototype.hasOwnProperty.call(nextSource,nextKey)){to[nextKey]=nextSource[nextKey];}}}}returnto;},writable: true,configurable: true});}
在业务工作中,如果你需要封装一个组件,你肯定会遇到这样的场景:组件的默认的配置对象defaultOption,需要与暴露出去的api进行合并,保证用户自定义的值能覆盖默认配置,但未定义的值取默认配置。其实,这本质上就是需要把defaultOption对象与外部传入的配置对象进行合并。我们经常会看到两种写法:
Object.assign
和$.extend
,那这两者有没有区别呢?Object.assign()和$.extend()用法
首先呈现官方文档:Object.assign()、jQuery.extend()。
Object.assign()
Object.assign(target, ...sources)
,Returns: Object$.extend()
jQuery.extend( target [, object1 ] [, objectN ] )
, Returns: ObjectjQuery.extend( [deep ], target, object1 [, objectN ] )
, If true, the merge becomes recursive(递归) (aka. deep copy,深拷贝).The Object.assign() method only copies enumerable and own properties from a source object to a target object.
$.extends(): Merge the contents of two or more objects together into the first object.
区别
两者区别其实不大:
true
可实现deep merge,而Object.assign只会copies that reference value
。Talk is Cheap, show me the code
deep merge
参考资料
(本篇完)
The text was updated successfully, but these errors were encountered: