目录

介绍

什么是Object.assign()?

JavaScript可枚举属性

语法和参数

您可以使用Object.assign()方法做什么?

合并对象

克隆对象

关于Object.assign()方法的注意事项

$.extend和Object.assign()之间的区别?

总结


介绍

第一次看到此方法时,我以为该方法可以帮助我复制对象或将对象合并为一个。当我习惯使用这种方法时,我变得越来越好奇,我想更多地了解它及其不同的行为。

这就是为什么本文将探讨此方法以及使用此方法时需要记住的事情。

好的,让我们开始吧。

什么是Object.assign()?

调用后,此方法会将值从一个或多个不同的对象复制到目标对象。此外,复制的值是对象拥有的所有可枚举属性。那些不了解可枚举属性,无后顾之忧的人,我们将一起学习并展示一个简单的示例。

JavaScript可枚举属性

JavaScript中的可枚举属性是可以使用for-in loop 或类似的迭代方法(例如Object.keys())访问的属性。

让我们举个简单的例子,说明如何检查属性是否可枚举。

/** Let's define an object with two properties*/
const desktop = {CPU: "Intel",Memory: "16GB"
};/** Let's define a property at runtime. * This property we'll set as non-enumerable.*/
Object.defineProperty(desktop, 'Operating_System', {value: "Windows 10",enumerable: false
});/* Let's try to iterate through the properties of the desktop object.* Expected: "CPU" "Memory"The property desktop won't appear as we iterate because the enumerable property is set to false.*/ for( let keys in desktop){console.log(keys);
}//Same as using Object.keys() methods
console.log(Object.keys(desktop));

这是上面的示例代码的步骤。

  1. 我们声明了一个具有两个属性的对象。这些属性是可枚举的(设置为true),这是JavaScript在创建对象时的默认行为。
  2. 在第二步中,我们使用static方法Object.defineProperty()将属性添加到对象并将其可枚举的属性设置为false。
  3. 然后,我们尝试了for-in循环和Object.keys() 方法。如预期的那样,这两个方法都可以获取CPU 和Memory 属性(除了属性OperatingSystem之外)。

语法和参数

回到该Object.assign()方法,我们将尝试探索其语法和参数。

对于语法,它看起来很简单。

Object.assign(target, ...sources)

一个参数是目标对象。简而言之,该target对象将是不同来源相结合的结果。

第二个参数是sources,他们是要应用的对象。

最后,此方法返回目标对象。

您可以使用Object.assign()方法做什么?

合并对象

使用Object.assign(),我们可以合并对象。

请参阅以下示例:

/*
* In this example, let's declare two objects, in our example, food and clothes.
* After that, let's try to merge the two objects into one.*///declare two objects
const food = { color: 'blue'};
const clothes = { brand: 'Guess'};
//merge two objects
const result = Object.assign({ companyName: "XYZ" }, food, clothes);//The output would be:{companyName: "XYZ", color: "blue", brand: "Guess"}
console.log(result); 

克隆对象

使用Object.assign(),我们可以克隆对象。

请参阅以下示例:

/** In this example, let's declare one object and clone it into an empty object. *///declare an object
const customer = { fName: 'Jin', lName: 'Necesario', handsome: true };
//clone the customer object
const clonedCustomer = Object.assign({}, customer);//The output would be: {fName: "Jin", lName: "Necesario", handsome: true}
console.log(clonedCustomer);

关于Object.assign()方法的注意事项

不会复制源的[[prototype]]属性。

让我们看下面的例子:

function Person(first, last, age, eyecolor) {this.firstName = first;this.lastName = last;this.age = age;this.eyeColor = eyecolor;
}const newPerson = new Person("jin", 'necesario', 100, 'brown');Person.prototype.nationality = "English";/*
* Person {firstName: "jin", lastName: "necesario", age: 100, eyeColor: "brown"}
* age: 100
* eyeColor: "brown"
* firstName: "jin"
* lastName: "necesario"
* __proto__:
* nationality: "English"
* constructor: ƒ Person(first, last, age, eyecolor)
* __proto__: Object
*/
console.log(newPerson);/*output english*/
console.log(newPerson.nationality);
console.log(newPerson.__proto__.nationality);let result = Object.assign({}, newPerson);console.log(result);/*undefined because no access to [[proto]]*/
console.log(result.nationality);
console.log(result.__proto__.nationality);

它不会复制gettersetter

让我们看下面的例子:

const customer = {fName: 'Jin',lName: 'Necesario',get fullName() {return this.lName + " " +  this.fName;},set fullName(value){const parts = value.split(" ");this.fName = parts[0];this.lName = parts[1];}
};let result = Object.assign({}, customer);/*
* We are showing that this object has a getter and setter that will be
* available in the target object
* {enumerable: true, configurable: true, get: ƒ, set: ƒ}
*   configurable: true
*   enumerable: true
*   get: ƒ fullName()
*   set: ƒ fullName(value)
*   __proto__: Object
*/console.log(Object.getOwnPropertyDescriptor(customer,'fullName'));/** Output: * { fName: "Jin", lName: "Necesario", fullName: "Necesario, Jin"}*/
console.log(result);/*
* Output:
* {value: "Necesario, Jin", writable: true, enumerable: true, configurable: true}
*  configurable: true
*  enumerable: true
*  value: "Necesario, Jin"
*  writable: true
*  __proto__: Object
*/
console.log(Object.getOwnPropertyDescriptor(result,'fullName'));

$.extend和Object.assign()之间的区别?

如果您一直在并行使用JQuery和Vanilla JS,则可能在JQuery中遇到过$.extend。您可能已经考虑或询问了两者之间的区别。

现在,在我看来,这些方法的目标是将对象克隆或合并为一个对象。

但是,主要区别在于Object.assign()进行浅层复制,而$.extend使用深层复制。

让我们在下面看一个例子。

let customer = {id: 1,details: {firstName: 'Jin',lastName: 'Necesario',tall: true}
};let customer2 = {id: 2,details: {firstName: 'Vincent'}
};let newCustomer = Object.assign({}, customer, customer2);
let newCustomer2 = $.extend(true, {}, customer, customer2);/*** output:* {details: {firstName: "Vincent"}id: 2}*/
console.log(newCustomer);/***  output:*  {*    details: {firstName: "Vincent", lastName: "Necesario", tall: true}*    id: 2*   }*/
console.log(newCustomer2); 

总结

这篇文章展示了Object.assign()方法实际上对代码示例有什么作用,并且还展示了处理该方法时需要注意的一些事项。

https://www.codeproject.com/Tips/5293257/The-Object-assign-Method-In-JavaScript

JavaScript中的Object.assign()方法相关推荐

  1. javascript中对象的assign()方法

    javascript中对象的assign()方法 Object.assign() 方法用于将所有可枚举属性的值从一个或多个源对象复制到目标对象.它将返回目标对象. 语法: Object.assign( ...

  2. JavaScript 复制对象与Object.assign方法无法实现深复制

    在JavaScript这门语言中,数据类型分为两大类:基本数据类型和复杂数据类型.基本数据类型包括Number.Boolean.String.Null.String.Symbol(ES6 新增),而复 ...

  3. Object.assign方法的使用和splice方法用法

    一.基本语法 Object.assign(target, ...sources) 二.基本概念 Object.assign方法用来将源对象(source)的所有可枚举属性,复制到目标对象(target ...

  4. es6 Object.assign()方法

    Object.assign()方法 基本用法 Object.assign()方法用于对象的合并,将源对象(source)的所有可枚举属性,复制到目标对象(target). const target = ...

  5. php中this的使用技巧,JavaScript中this关键字使用方法详解

    JavaScript中this关键字使用方法详解 在面向对象编程语言中,对于this关键字我们是非常熟悉的.比如C++.C#和Java等都提供了这个关键字,虽然在开始学习的时候觉得比较难,但只要理解了 ...

  6. js两个问号代表什么_js中的Object.assign接受两个函数为参数的时候会发生什么?...

    缘由 今天看到一段代码 return Object.assign(func1, func2); 心生疑惑,为什么 Object.assign 的参数可以是函数? 于是有了下面这一堆东西,其实都是老生常 ...

  7. Object.assign()方法

    1.对象的扩展 ES6中,对象的属性和方法可简写:对象的属性值可不写,前提是属性名已经声明: var name = "zhangsan";var password = " ...

  8. Object.assign() 方法的使用详解

    Object.assign() 方法用于将所有可枚举属性的值从一个或多个源对象复制到目标对象.它将返回目标对象. 注意: 会改变源对象 语法: Object.assign(target, ...sou ...

  9. 区分JavaScript中slice与splice方法

    区分JavaScript中slice与splice方法 slice()方法是从已有的数组中返回通过索引选定的元素. 语法:array.slice(startIndex,endIndex) 参数star ...

最新文章

  1. 基于SCVMM对虚拟化服务器与虚拟机管理权限分配用户角色
  2. Scala mapValues踩坑记:谨慎使用Scala Map的mapValues, 你需要的可能是transform
  3. windows和centos进行文件上传和下载
  4. Modbus通信协议之CRC16冗余循环校验函数
  5. 烟花程序c语言,C语言烟花程序
  6. Python精通-Python学习路线详细介绍
  7. Bailian2980 大整数乘法【大数】
  8. 数学中的皇冠——数论
  9. flask中的jinjia2模板引擎详解1
  10. 游戏建模资料大放送,3DMX+MAYA+ZBrush集教程,20G教学视频
  11. python指纹识别_Python实现指纹识别你见过没?
  12. Hyperledger Fabric金融区块链项目总结 之一 概述
  13. edge和chrome自动添加九九购和其他插件问题
  14. 网络摄像头IPC国标GB28181协议国标安防视频流媒体平台EasyGBS视频流不上线排查步骤
  15. python基础day-15:time、hash、json
  16. idea中,maven窗口功能图标含义
  17. caffe安装详细完整过程(Ubuntu16.04、Ubuntu18.04系统)
  18. JS对DOM节点的操作--增加节点,删除节点
  19. 在Oracle中执行动态SQL的几种方法------转载
  20. 给定一个单词,如果该单词以er、ly或者ing后缀结尾, 则删除该后缀(逐句精解)

热门文章

  1. 如何去选取第一批要阅读的论文?_顶会最佳论文奖得主:初入科研领域,如何正确做科研?...
  2. 期刊投稿状态_论文投稿,你不知道的那些事
  3. oss图片尺寸调用方式_CDN百科11 | 如何用CDN加速OSS源站资源
  4. fastreport文本字数太多换行_Python教程第10篇:聊聊print换行输出和重复多次打印...
  5. mysql master线程 fork_多线程中fork的坑
  6. tpc-c 服务器性能,IBM创英特尔8处理器服务器TPC-C性能记录
  7. 设计师社区网站-交流、学习、展示
  8. 湖南高工计算机考试,湖南一工教育
  9. mysql5.5索引如何定义_MySQL5.5索引数在InnoDB引擎内与索引数在mysql中定义的数量是不一致问题-阿里云开发者社区...
  10. Qemu Tracing