What does the object[foo] term mean?

后端 未结 3 1000
孤独总比滥情好
孤独总比滥情好 2021-01-21 02:34

I\'m confused what the object[foo] term is referring to. Any hints? I know that bar[\'unique_prop\'] and bar.unique_prop refers to

相关标签:
3条回答
  • 2021-01-21 03:13

    This:

    var foo = 'abc';
    object[foo]
    

    is equivalent to:

    object.abc
    

    However this:

    var foo = {unique_prop: 1};
    object[foo] = 'value';
    

    Doesn't have much sense (object property names cannot be object literals). JS engine will use foo.toString() (returning e.g. "[object Object]"), so in fact you are doing this:

    var foo = {unique_prop: 1};
    object["[object Object]"] = 'value';
    

    which is clearly a bug or a misunderstanding. This behaviour is explained in Member Operators on MDN:

    Property names must be strings. This means that non-string objects cannot be used as keys in the object. Any non-string object, including a number, is typecasted into a string via the toString method.

    You can however use:

    object[foo.unique_prop] = 'value';
    

    which is equivalent to:

    object[1] = 'value';
    
    0 讨论(0)
  • 2021-01-21 03:16
    object[foo] = 'value';
    

    attempts to use an object as a member name, this causes a .toString() call so;

    'value' is assigned to object["[object Object]"], when you attempt to read alert(object[bar]); the same toString() occurs as bar is also an object, so you reference object["[object Object]"] once again and get back 'value'.

    0 讨论(0)
  • It is the same as object.whatever_x_is where x is foo.toString() which will be the same as bar.toString() since (unless overridden) calling toString on a generic object will generate a generic "is an object" string such as "[object Object]"

    0 讨论(0)
提交回复
热议问题