JavaScript: Access own Object Property inside Array Literal

人走茶凉 提交于 2019-11-27 23:14:44
CMS

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.

The this property does not point to the closure object. If we were to define the myPic property on the global scope, then you will see picArray initialized with that value. Consider this example:

<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 is one of the hardest concepts in JavaScript. You might like this article on the topic.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!