Does a Javascript object property, available through parentheses, assign a different property value?

I know what the following code does, I just can't wrap my head around WHY.

var myObject = new Object();
var foo = new Object();
var bar = new Object();

myObject[foo] = 'foo';
myObject[bar] = 'bar';
console.log(myObject[foo]);  // returns bar
console.log(myObject); // returns [object Object]: "bar"
console.log(myObject[blah]); // returns "blah not defined" error.

To this extent, how is myObject [blah] undefined, but myObject [foo] and myObject [bar] are defined - and not only defined, but set to the same value?

According to http://www.w3schools.com/js/js_objects.asp the properties of the object can be obtained through object.property or object[property] , however, if I add in myObject.foo = "foobar";front of the console logs, myObject[foo]it is not set to "foobar", but myObject.foodoes.

If I console.log myObject.Objector myObject.Objector myObject[object]or myObject[object]- it all returns as undefined.

foo bar Object {}. .

+4
3

.

foo - , .

foo , , , , :

myObject[foo] = 'foo';
myObject[bar] = 'bar';

myObject["[object Object]"] = 'foo';
myObject["[object Object]"] = 'bar';

, myObject [blah] undefined myObject [foo] myObject [bar] - , ?

, , . , blah - , , , undefined.


, , {} new Object()

+4

blah, .

foo bar, . JavaScript HashMaps , , "[object Object]".

, myObject[foo] myObject[bar] myObject["[object Object]"]

myObject["foo"] myObject["bar"] "?

:

obj["property"];
// or
obj.property;
// or
var prop = "property";
obj[prop];
+2
  • , myObject [blah] undefined

myObject[blah] undefined, blah, , undefined ( , )

var blah= new Object();

myObject[blah] .

  • myObject [foo] myObject [bar] ,

, , foo bar,

var foo = new Object();
var bar = new Object();

, , ,

myObject[foo] = 'foo';
myObject[bar] = 'bar';

, . myObject.foo, ', , ' foo '' myobject '.

,

myobject["foo"] //-> NOTE foo is a string. A property is created.

,

var foo = new object();
myobject[foo] // this is not correct since foo is an object here not a string 
//or a property. inshort adding objects as property not a good idea.
  • console.log myObject.Object myObject.object myObject [object] myObject [Object] - undefined.

    myObject.Object// myobject

    no property called "Object", "object"

However, if you say

myObject.object = "added object property"; //OR
myObject["object"] = "added object property";

then try the console.log commands above, they should work, but note that the properties are case sensitive

0
source

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


All Articles