[Javascript] How javascript read the property?

Zhentiw發表於2024-10-08

As we know we can read property value from an object as so:

const obj = {}

obj.xxxx;
obj[xxxx];

So what's the difference between those two?

obj.x

ECMAScript will do a transform internally as such

[[GET]](obj /*object itself*/, 'x' /*property key*/, obj /*this pointer*/)

obj[x]

ECMAScript will do a transform internally as such

[[GET]](
    obj /*object itself*/, 
    x is symbol ? x: String(x) /*check whether x is symbol, if is, then use symbol, otherwise stringify x*/, 
    obj /*this pointer*/
)

So as we can see, the only difference between those two is how ECMAScript handle x property key.

obj.x: consider 'x' as string value

obj[x]: consider x can be smybol or not, if yes, will use symbol, otherwise, convert to string value

Examples

const obj = {}
obj[0] = 1 // is 0 a symbol? nope, then conver to '0'
obj['0'] = 2 // is '0' a symbol? nope, then keep '0'
console.log(obj) // {'0': 2}

const obj = {}

obj[obj] = 1 // is obj a symbol? nope, then String(obj) which is '[object object]'
console.log(obj) // {'[object Object]': 1}

const obj = {
  toString() {
    return 'abc'
  }
}

obj[obj] = 1 // is obj a symbol? nope, then String(obj) which is 'abc'
console.log(obj) // {toString: [Function: toString], 'abc': 1}

相關文章