Understanding Object Literals

In almost a few examples, I came across the following example:

var foo = {unique_prop: 1};
var bar = {unique_prop: 2};
var object = {};
object[foo] = 'value';
alert(object[bar]);

where two objects foo and bar are created. I do not get a warning (object [bar]); is the "value". What is the connection here between foo and bar.

In addition, a small change will give the result as "undefined" as an example below.

var foo = {unique_prop: 1};
var bar = {unique_prop: 2};
var object = {};
object["foo"] = 'value';
alert(object[bar]);

By default, the notation []can be used on the right line, arent ["some_property"], and [some_property]the same thing?

+4
source share
2 answers

, , . , .

var foo = {unique_prop: 1};
var bar = {unique_prop: 2};
var object = {};

object[foo] = 'value';
// foo is an object, so it automatically turned into the string "[object Object]"
// so the above code is equivalent to `object["[object Object]"] = 'value';`

alert(object[bar]);
// bar is also an object, so is converted into the same string
// the above code is also equivalent to `alert(object["[object Object]"]);` which of course accesses that same value

var blah = "not blah";
object.blah = 1;
object["blah"] = 1;

object[blah];
// a variable is used.
// therefore the value of that variable is what the assessor is looking for, not the name of the variable.
// so the above code is equivalent to `object["not blah"];`.
+6

*, , , , .

ECMAScript 6 Map, , . :

const foo = {unique_prop: 1}
const bar = {unique_prop: 2}
const map = new Map()
map.set(foo, 'value')
console.log(map.get(bar)) // undefined

* ECMAScript 6 , .

0

Source: https://habr.com/ru/post/1653290/


All Articles