简体   繁体   English

当我在javascript中'Object.assign`到原始类型时会发生什么?

[英]What happens when I `Object.assign` to a primitive type in javascript?

I discovered that you can call Object.assign on a string or number type in javascript to get a sort of 'enhanced' primitive type. 我发现你可以在javascript中调用stringnumber类型的Object.assign来获得一种“增强的”原始类型。

// closure used to create object for simplicity
function makeObj() {

    let value = 6;

    let enhancedValue = Object.assign(value, {
        set: () => 'from the set method'
    })

    return {
        someValue: enhancedValue
    };
}

let myObj = makeObj();

// output is from nodejs

console.log(myObj.someValue); // accessing
// outputs: `{ [Number: 6] set: [Function: set] }`
console.log(myObj.someValue + 3); // using
// outputs: `9`
console.log(myObj.someValue.set()) // using method
// outputs: `from the set method`

So my question is: what type is this now? 所以我的问题是:现在这是什么类型的? Is there any spec defining this behavior? 是否有任何规范定义此行为? Is there any reason not to do this? 有什么理由不这样做吗? Could you explain what's going on here? 你能解释一下这里发生了什么吗?

In JavaScript, almost all primitive types have an equivalent object type. 在JavaScript中,几乎所有基本类型都具有等效的对象类型。 So while "x" is a string primitive, new String("x") is a String object. 因此,虽然"x"是字符串基元,但new String("x")是String对象。 Similarly, there are number primitives and Number objects, and boolean primitives and Boolean objects, etc. 类似地,有数字基元和Number对象,布尔基元和Boolean对象等。

The first step of Object.assign is to take the first argument and use the abstract ToObject operation on it, which performs that primitive-to-object step. Object.assign第一步是获取第一个参数并对其使用抽象ToObject操作 ,该操作执行该原始到对象的步骤。 From that point forward, it uses the object returned by ToObject. 从那时起,它使用ToObject返回的对象。 (ToObject just returns its argument if it's already an object.) (ToObject只返回它的参数,如果它已经是一个对象。)

That object is what assign ultimately returns. 该对象是assign最终返回的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM