Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Access own Object Property inside Array Literal

Given an Array Literal inside a JavaScript Object, accessing its own object's properties does not seem to work:

 var closure =  {

         myPic : document.getElementById('pic1'),
         picArray: [this.myPic]
 }    

 alert(closure.picArray[0]); // alerts [undefined]


Whereas declaring an Array Item by accessing an other JavaScript Object seem to work

 ​var closure1 = {
 ​    
 ​     myPic : document.getElementById('pic1')
 ​}
 ​    
 ​var closure2 =  {
 ​  
 ​        picArray: [closure1.myPic]
 ​}    
 ​    
 ​alert(closure2.picArray[0]); // alerts [object HTMLDivElement]


Example: http://jsfiddle.net/5pmDG/

like image 641
stevek-pro Avatar asked Jul 25 '10 19:07

stevek-pro


People also ask

What are the different ways to access object properties in JavaScript?

The keys in this array are the names of the object's properties. There are two ways to access properties: dot notation and bracket notation.

How do you access data from an array of objects?

You can access a nested array of objects either using dot notation or bracket notation. JavaScript has only one data type which can contain multiple values: Object. An Array is a special form of an object. Both arrays and objects expose a key -> value structure.

How do I access nested objects?

The sub-properties of objects can be accessed by chaining together the dot or bracket notation .


1 Answers

The this value will not work like that, it refers to a value determined by the actual execution context, not to your object literal.

If you declare a function member of your object for example, you could get the desired result:

var closure =  {
  myPic: document.getElementById('pic1'),
  getPicArray: function () {
    return [this.myPic];
  }
};
//...
closure.getPicArray();

Since the this value, inside the getPicArray function, will refer to your closure object.

See this answer to another question, where I explain the behavior of the this keyword.

Edit: In response to your comment, in the example that I've provided, the getPicArray method will generate a new Array object each time it is invoked, and since you are wanting to store the array and make changes to it, I would recommend you something like this, construct your object in two steps:

var closure =  {
  myPic: document.getElementById('pic1')
};
closure.picArray = [closure.myPic];

Then you can modify the closure.picArray member without problems.

like image 71
Christian C. Salvadó Avatar answered Sep 18 '22 00:09

Christian C. Salvadó