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/
The
thisvalue 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:
Since the
thisvalue, inside thegetPicArrayfunction, will refer to yourclosureobject.See this answer to another question, where I explain the behavior of the
thiskeyword.Edit: In response to your comment, in the example that I’ve provided, the
getPicArraymethod 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:Then you can modify the
closure.picArraymember without problems.