了解Javascript对象代码段

Understanding Javascript Object Code Snippet

本文关键字:代码 对象 Javascript 了解      更新时间:2023-09-26

我在Mozilla开发者网络(MDN)上看到了这个代码片段,我绞尽脑汁想弄清楚为什么结果确实是"值"

var foo = {unique_prop: 1}, bar = {unique_prop: 2}, object = {};
object[foo] = 'value';
console.log(object[bar]);

如果有人能开导我,我将不胜感激!

object[foo] = 'value';

您只能将字符串作为标识符,因此当运行上述程序时,JavaScript会在内部调用代表"[object Object]"ToString方法。这就是对象的表示方式。

现在,当您执行object[bar]时,bar.toString()也是"[object Object]",并且由于'value'是以"[object Object]"作为密钥存储的,因此它会被返回。

如果您在控制台中快速查看,您会发现这是因为foo被强制为string(因为Javascript中的所有键都是字符串**),默认为[object object]。字符串[object object]对于每个对象都是相同的,因此foo看起来是bar,但本质上不是。查看以下输出:

var foo = {unique_prop: 1}, bar = {unique_prop: 2}, object = {};
object[foo] = 'value';
var output = document.getElementById('p')
for(thing in object){
  output.textContent += thing + " = " + object[thing];
}
<p id='p'></p>

**我认为ES6有一种使用{[func]: value}语法设置计算密钥的方法,但我还没有深入研究,所以请原谅我可能的错误。

您可以在这里看到3个小型实验的进展:

  1. 对您创建的每个对象调用toString()的结果是什么?

    foo.toString()bar.toString()object.toString()输出:

    [object Object]
    
  2. object[{}]的结果是什么?

    它也是"value",因为运行时用来存储值的密钥实际上是[object Object]

  3. 让我们改变toString的行为,看看会发生什么。

    Object.prototype.toString = function(){
      return this.unique_prop;
    };
    // Re run the code
    object[foo] = "value";
    console.log(object[bar]);  // Returns undefined
    // Value was stored under the key "1"
    console.log(object[1]);  // Returns "value"
    

因为这个对象中的键是foo和bar对象的字符串表示,比如 Object {[object Object]: "value"}

如上所述,使用对象字符串设置对象属性结果将生成关键

> console.log(foo.toString())
[Log] [object Object]

所以object[foo]相当于

object["[object Object]"] = 'value';

然而,如果你真的想让它们与众不同,你可以这样做:

> console.log(JSON.stringify(foo))
[Log] {"unique_prop":1}
> object[JSON.stringify(foo)] = 'donkey'
> console.log(object)
[Log] {[object Object]: "value", {"unique_prop":1}: "donkey"}
> console.log(object[JSON.stringify(bar)])
[Log] undefined