首页 > 解决方案 > 在对象文字内分配数值不会引发任何错误

问题描述

考虑以下代码:

let logged = 1;
let x = {logged} //{logged: 1} 
x['logged']; // 1
x['logged']['index']; //undefined
x['logged']['index'] = 0; 
x; // {logged: 1}
x['logged']['index']; //undefined

所以,我的问题是:不是

我在 nodejs 终端上测试了这个,节点版本为 14.16.0

标签: javascriptnode.js

解决方案


不确定我上面的评论是否真的为您完全阐明了这个问题。

我编写了一个小程序,可能有助于可视化发生的情况。请注意,我正在对原始值而不是常规属性查找进行方法查找 - 但这都是一样的,并且可以更好地说明发生了什么。

function captureThis() {
    return this
}
(function setUpObjectPrototype() {
    if (Object.prototype.captureThis !== undefined) throw new Error("Couldn't set up Object prototype properly.")
    Object.prototype.captureThis = captureThis
    process.nextTick(() => delete Object.prototype.captureThis)
})()

var number = 1
var thisObject = number.captureThis()

console.log("Is thisObject an object? " + (typeof thisObject == "object"))
console.log("Is number still just a number? " + (typeof number == "number"))
console.log("Is thisObject an instance of Number? " + (thisObject instanceof Number))

// Output
// Is thisObject an object? true
// Is number still just a number? true
// Is thisObject an instance of Number? true

请注意,数字变量在任何时候都不会实际强制转换为对象——创建了一个临时对象来包装数字变量中包含的值。该对象实际上从未分配给变量 - 除非它像在这个小程序中一样被捕获。

希望这会有所帮助。


推荐阅读