darkknight
darkknight

Reputation: 5

How javascript is managing Object property name as Object which changes dynamically?

I was looking in docs on MDN and found that Object poperty names can be Object(which will be converted to string). I wrote a simple code to test it out and it worked but later changing the obj which is being assigned as a key to main Object,should change the resulted key (string representation) thus the Main object property should not be accesible with new object but It is accesible.

I wanna know how javascript it managing this?

var objee = {};
var rajat = "me";
var rand = Math.random();
var ob = new Object();

objee[ob] = "hey";


console.log(ob,objee[ob]);//javascript is converting the Object key to string using Object.toString().

ob.name = "rajat";

// Why this property is still accesible if the "ob" has changed now..and resulted string is changed,thus key changed?

console.log(ob,objee[ob]);

I know this is question is very confusing..Hope you will understand.

Upvotes: 0

Views: 33

Answers (2)

Quentin
Quentin

Reputation: 944011

The object might have changed, but its string representation has not:

var ob = new Object();
console.log(ob.toString());
ob.name = "foo";
console.log(ob.toString());

… so the property name being referenced by it is also unchanged.

Upvotes: 1

hairmot
hairmot

Reputation: 2975

As you have commented, the name of the key referenced by the ob object is the value of ob.toString(). When you call this, it will return '[object Object]'

This means that the key name is '[object Object]'. This will not change even if you change the value of ob.name as ob.toString() still outputs [object Object]

If you call console.log(ob), you will see the property name output as above.

See this article for more details

Upvotes: 0

Related Questions