admin管理员组文章数量:1330643
I have a object literal:
var obj = {
a : document.getElementById("ex1"),
b : obj.a.document.getElementsByTagName("div")
};
I am having trouble with the b property, for some reason it is not letting that happen. Is this possible?
I have a object literal:
var obj = {
a : document.getElementById("ex1"),
b : obj.a.document.getElementsByTagName("div")
};
I am having trouble with the b property, for some reason it is not letting that happen. Is this possible?
Share Improve this question asked Feb 16, 2012 at 19:23 bryan sammonbryan sammon 7,44116 gold badges40 silver badges51 bronze badges 1- 1 possible duplicate of Self-references in object literal declarations – zzzzBov Commented Jun 18, 2013 at 20:29
3 Answers
Reset to default 6The modern way to do this is with getter methods:
let obj = {
firstName: "A’dab",
lastName: "Farooqi"
get fullName() {
return this.firstName+" "+this.lastName;
},
}
So now you can just write obj.fullName
- no need for the parentheses on the end.
You need two steps:
var obj = {
a : document.getElementById("ex1")
};
obj.b = obj.a.document.getElementsByTagName("div")
Or:
var temp = document.getElementById("ex1")
var obj = {
a : temp,
b : temp.document.getElementsByTagName("div")
};
When the property b
is being defined, obj
is not defined yet. One way to get around that problem is to make your property a function so that it's not evaluated until called.
var obj = {
a : document.getElementById("ex1"),
b : function() {
// This is not evaluated until obj.b() is called
return obj.a.document.getElementsByTagName("div");
}
};
obj.b();
If you really want it to be a property, you have to do it in two steps as Tomasz Nurkiewicz shows
版权声明:本文标题:Javascript Object Literal referring to another property in itself from another property - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742227189a2436540.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论