[removed] Access own Object Property inside Array Literal

前端 未结 2 1296
暖寄归人
暖寄归人 2020-12-06 07:36

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

 var closure =  {

         myPic : document         


        
2条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-06 07:59

    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.

提交回复
热议问题