JavaScript: accessing a native object Property inside a Literal array

Given an array literal inside a JavaScript object, accessing its own object properties does not seem to work:

 var closure =  {

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

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


Whereas declaring an element of an array by accessing another JavaScript object works

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


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

+5
source share
2 answers

The value thiswill not work like this, it refers to the value determined by the context of the actual execution, and not to your object literal.

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

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

this, getPicArray, closure.

, this.

: , , , getPicArray Array , - , :

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

closure.picArray.

+9

this closure. myPic , picArray, . :

<script>
window.myPic = "Global myPic";

var closure =  {
    myPic : document.getElementById('pic1'),
    picArray: [this.myPic] // this refers to the global object
};

console.log(closure.picArray); // ["Global myPic"];
</script>

this - JavaScript. .

+2

All Articles