JavaScript中的Object.assign()方法

目录

介绍

什么是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'));

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

如果您一直在并行使用JQueryVanilla 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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值