JS Class with static method not seeing static setter

Viewed 2387

I have this simple code -

class Repo {
    constructor(someParam = null) {
        this.getDic = someParam;
    }
    static set getDic(ref){
        this.ref = ref;
    }
    static get getDic(){
        return this.ref;
    }
    static key(key){
        return this.getDic[key];
    }
}

let newRepo = new Repo({yeah: 'baby'});
Repo.key('yeah') // Uncaught TypeError: Cannot read property 'yeah' of undefined

Why is the 'getDic' getter undefined in the 'key' static method?

Thanks!

2 Answers

I had a very similar problem; it turns out this doesn't refer to the static class the way you'd expect. Using the actual classname fixes it. So:

class Repo {
    . . .
    static key(key){
        return Repo.getDic[key];
    }
}

By swapping out the this for the classname, it should work properly.

Related