当前位置:   article > 正文

JavaScript中的Object.assign()方法_js object assign方法

js object assign方法

目录

介绍

什么是Object.assign()?

JavaScript可枚举属性

语法和参数

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

合并对象

克隆对象

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

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

总结


介绍

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

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

好的,让我们开始吧。

什么是Object.assign()

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

JavaScript可枚举属性

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

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

  1. /*
  2. * Let's define an object with two properties
  3. */
  4. const desktop = {
  5. CPU: "Intel",
  6. Memory: "16GB"
  7. };
  8. /*
  9. * Let's define a property at runtime.
  10. * This property we'll set as non-enumerable.
  11. */
  12. Object.defineProperty(desktop, 'Operating_System', {
  13. value: "Windows 10",
  14. enumerable: false
  15. });
  16. /* Let's try to iterate through the properties of the desktop object.
  17. * Expected:
  18. "CPU"
  19. "Memory"
  20. The property desktop won't appear as we iterate
  21. because the enumerable property is set to false.
  22. */
  23. for( let keys in desktop){
  24. console.log(keys);
  25. }
  26. //Same as using Object.keys() methods
  27. 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(),我们可以合并对象。

请参阅以下示例:

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

克隆对象

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

请参阅以下示例:

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

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

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

让我们看下面的例子:

  1. function Person(first, last, age, eyecolor) {
  2. this.firstName = first;
  3. this.lastName = last;
  4. this.age = age;
  5. this.eyeColor = eyecolor;
  6. }
  7. const newPerson = new Person("jin", 'necesario', 100, 'brown');
  8. Person.prototype.nationality = "English";
  9. /*
  10. * Person {firstName: "jin", lastName: "necesario", age: 100, eyeColor: "brown"}
  11. * age: 100
  12. * eyeColor: "brown"
  13. * firstName: "jin"
  14. * lastName: "necesario"
  15. * __proto__:
  16. * nationality: "English"
  17. * constructor: ƒ Person(first, last, age, eyecolor)
  18. * __proto__: Object
  19. */
  20. console.log(newPerson);
  21. /*output english*/
  22. console.log(newPerson.nationality);
  23. console.log(newPerson.__proto__.nationality);
  24. let result = Object.assign({}, newPerson);
  25. console.log(result);
  26. /*undefined because no access to [[proto]]*/
  27. console.log(result.nationality);
  28. console.log(result.__proto__.nationality);

它不会复制gettersetter

让我们看下面的例子:

  1. const customer = {
  2. fName: 'Jin',
  3. lName: 'Necesario',
  4. get fullName() {
  5. return this.lName + " " + this.fName;
  6. },
  7. set fullName(value){
  8. const parts = value.split(" ");
  9. this.fName = parts[0];
  10. this.lName = parts[1];
  11. }
  12. };
  13. let result = Object.assign({}, customer);
  14. /*
  15. * We are showing that this object has a getter and setter that will be
  16. * available in the target object
  17. * {enumerable: true, configurable: true, get: ƒ, set: ƒ}
  18. * configurable: true
  19. * enumerable: true
  20. * get: ƒ fullName()
  21. * set: ƒ fullName(value)
  22. * __proto__: Object
  23. */
  24. console.log(Object.getOwnPropertyDescriptor(customer,'fullName'));
  25. /*
  26. * Output:
  27. * { fName: "Jin", lName: "Necesario", fullName: "Necesario, Jin"}
  28. */
  29. console.log(result);
  30. /*
  31. * Output:
  32. * {value: "Necesario, Jin", writable: true, enumerable: true, configurable: true}
  33. * configurable: true
  34. * enumerable: true
  35. * value: "Necesario, Jin"
  36. * writable: true
  37. * __proto__: Object
  38. */
  39. console.log(Object.getOwnPropertyDescriptor(result,'fullName'));

$.extendObject.assign()之间的区别?

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

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

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

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

  1. let customer = {
  2. id: 1,
  3. details: {
  4. firstName: 'Jin',
  5. lastName: 'Necesario',
  6. tall: true
  7. }
  8. };
  9. let customer2 = {
  10. id: 2,
  11. details: {
  12. firstName: 'Vincent'
  13. }
  14. };
  15. let newCustomer = Object.assign({}, customer, customer2);
  16. let newCustomer2 = $.extend(true, {}, customer, customer2);
  17. /**
  18. * output:
  19. * {
  20. details: {firstName: "Vincent"}
  21. id: 2
  22. }
  23. */
  24. console.log(newCustomer);
  25. /**
  26. * output:
  27. * {
  28. * details: {firstName: "Vincent", lastName: "Necesario", tall: true}
  29. * id: 2
  30. * }
  31. */
  32. console.log(newCustomer2);

总结

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

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/68287
推荐阅读
相关标签
  

闽ICP备14008679号