JavaScript的:数组文本内访问自己的对象属性 [英] JavaScript: Access own Object Property inside Array Literal
问题描述
,访问自己的对象的属性似乎不工作:
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]
推荐答案
的这个
值不会喜欢这项工作,它是指通过实际执行上下文确定的值,而不是你的对象文本。
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();
由于这个
值时, 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.
编辑:在回答您的意见,因为我提供的例子中, getPicArray
方法将生成一个新的数组对象的每个一次调用,因为你是想存储阵列,并进行更改,我建议你这样的事情,你的构造对象分为两步:
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
成员没有任何问题。
这篇关于JavaScript的:数组文本内访问自己的对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!