简体   繁体   中英

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 .

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 . But obviously, they still contain 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?

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:

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM