【发布时间】:2017-03-02 16:18:26
【问题描述】:
我发现您可以在 javascript 中调用 string 或 number 类型的 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`
所以我的问题是:现在这是什么类型的?有没有定义这种行为的规范?有什么理由不这样做吗?你能解释一下这里发生了什么吗?
【问题讨论】:
-
所有原始类型都可以“装箱”成对象。有
Number原型、String原型等。 -
基本上是一个带有额外属性的
new Number(6)对象
标签: javascript