JavaScript:在 Array Literal 中访问自己的对象属性 [英] JavaScript: Access own Object Property inside Array Literal

查看:32
本文介绍了JavaScript:在 Array Literal 中访问自己的对象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个 JavaScript 对象内的数组字面量,访问它自己的对象的属性似乎不起作用:

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]


而通过访问其他 JavaScript 对象来声明数组项似乎有效


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]


例子:http://jsfiddle.net/5pmDG/

推荐答案

this 值不会这样工作,它指的是由实际执行上下文确定的值,而不是您的对象字面量.

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();

由于 this 值,在 getPicArray 函数中,将引用您的 closure 对象.

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

参见另一个问题的这个答案,在那里我解释了this 关键字.

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

为了回应您的评论,在我提供的示例中,getPicArray 方法将在每次调用时生成一个新的 Array 对象,并且由于您想要存储数组并对其进行更改,我建议您使用这样的方法,分两步构建您的对象:

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];

然后你可以毫无问题地修改closure.picArray成员.

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

这篇关于JavaScript:在 Array Literal 中访问自己的对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆