JavaScript:访问数组文字中自己的对象属性
给定 JavaScript 对象内的数组文字,访问其自身对象的属性似乎不起作用:
var closure = {
myPic : document.getElementById('pic1'),
picArray: [this.myPic]
}
alert(closure.picArray[0]); // alerts [undefined]
而通过访问其他 JavaScript 对象来声明数组项似乎可行
var closure1 = {
myPic : document.getElementById('pic1')
}
var closure2 = {
picArray: [closure1.myPic]
}
alert(closure2.picArray[0]); // alerts [object HTMLDivElement]
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/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
this
值不会那样工作,它指的是由实际执行上下文确定的值,而不是对象字面量。例如,如果您声明对象的函数成员,则可以获得所需的结果:
因为
getPicArray
函数内的this
值将引用您的闭包对象。
请参阅另一个问题的此答案,其中我解释了
this
关键字。编辑:为了回应您的评论,在我提供的示例中,
getPicArray
方法将在每次调用时生成一个新的 Array 对象,并且因为您想要存储数组并对其进行更改,我建议您这样做,分两步构建对象:然后您可以毫无问题地修改
closure.picArray
成员。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:
Since the
this
value, inside thegetPicArray
function, will refer to yourclosure
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:Then you can modify the
closure.picArray
member without problems.this
属性不指向closure
对象。如果我们要在全局范围内定义 myPic 属性,那么您将看到使用该值初始化的picArray
。考虑这个例子:this
是 JavaScript 中最难的概念之一。您可能会喜欢这篇关于该主题的文章。The
this
property does not point to theclosure
object. If we were to define the myPic property on the global scope, then you will seepicArray
initialized with that value. Consider this example:this
is one of the hardest concepts in JavaScript. You might like this article on the topic.