[英]Assign reference of a non-existent property into a variable
This might be a stupid problem, but I have an object in which I wanted to store references of other functions/variables and later use them. 这可能是一个愚蠢的问题,但是我有一个对象,我想在其中存储其他函数/变量的引用,以后再使用它们。
For example, 例如,
var obj = {
keyA: {
ref: window.objects.someAAA
},
keyB: {
ref: window.objects.someBBB
}
}
Here, when I set this object, window.objects
is empty, so accessing those keys ( someAAA
and someBBB
) will give undefined
. 在这里,当我设置此对象时, window.objects
为空,因此访问这些键( someAAA
和someBBB
)将给出undefined
。
I know I was dumb when I first thought of assigning them like this and expecting their actual values after they're loaded, to be available via obj.keyA
and obj.keyB
. 我知道我第一次想到要像这样分配它们,并期望它们在加载后可以通过obj.keyA
和obj.keyB
获得的实际值时是obj.keyB
。 But obviously, they still contain undefined
. 但显然,它们仍然包含undefined
。
But is there a way to do that! 但是有办法做到这一点! I know if I set string instead of reference, I can eval
, but any better solution? 我知道如果我设置字符串而不是引用,我可以eval
,但是还有更好的解决方案吗?
Think this should work 认为这应该工作
var obj = {
keyA: {
ref: function() { return window.objects.someAAA; }
},
keyB: {
ref: function() { return window.objects.someBBB; }
}
}
You can then access via 然后,您可以通过访问
obj.keyA.ref()
Test 测试
Add the code above then do 在上面添加代码,然后执行
window['objects'] = {};
window['objects']['someAAA'] = 'Hallo';
obj.keyA.ref() // will Output 'Hallo'
Try using Getters for such case: 在这种情况下,请尝试使用Getters :
var obj = {
get keyA(){
return (window['objects'])? window.objects.someAAA : null
},
get keyB() {
return (window['objects'])? window.objects.someBBB : null
}
}
// as now window.objects doesn't exists
console.log(obj.keyA); // outputs "null"
window.objects = {'someAAA': "aaa-value", 'someBBB': "bbb-value"};
console.log(obj.keyA, obj.keyB); // outputs "aaa-value" "bbb-value"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.