0

Is there a way to define a get/set method adhoc? I have a module that encapsulates the localStorage:

const ACCESS_TOKEN = "ACCESS_TOKEN";

export const getString = key => {
    return localStorage.getItem(key);
};

export const setString = (key, value) => {
    localStorage.setItem(key, value);
};


export default {
    get accessToken() {
        return getString(ACCESS_TOKEN);
    },
    set accessToken(value) {
        setString(ACCESS_TOKEN, value);
    },
};

And I want to generate it in runtime:

let obj;

obj["accessToken"] = get() {
 return getString(ACCESS_TOKEN);
}

obj["accessToken"] = set(value) {
      setString(ACCESS_TOKEN, value);
}

export default obj;

This answer does not help as it seems you can only use Object.defineProperty to define simple getters and setters and not custom logic.

Guy
  • 12,488
  • 16
  • 79
  • 119
  • 1
    You can pass getters and setters to `Object.defineProperty` – CertainPerformance Sep 03 '19 at 08:45
  • How do you want to interact with `obj['func']`? Do you want to call `obj['func'].set()` and `obj['func'].get()`? Or do you want it to happen automatically when you do `obj['func'] = 2` – TKoL Sep 03 '19 at 08:45
  • @TKoL Tnx, I've added the usage in the question – Guy Sep 03 '19 at 08:47
  • @CertainPerformance I've elaborated why the answer provided does not cover my use case. Could you possibly remove the duplicate flag? – Guy Sep 03 '19 at 08:55
  • 1
    Since getters and setters are functions, you can use all the custom logic you wish inside each function, right? https://jsfiddle.net/vewh3ky9/ – CertainPerformance Sep 03 '19 at 08:57
  • @CertainPerformance Sorry, I was looking at the 2013 answer and not the 2015 Proxy update. Perhaps I should have another cup of coffee ;-) Tnx – Guy Sep 03 '19 at 09:01
  • 1
    That's a lot more complicated than you need - the `Object.defineProperty` method described in the 47-upvote answer looks the simplest and best suited. Also see https://stackoverflow.com/questions/812961/getters-setters-for-dummies#answer-34845963 – CertainPerformance Sep 03 '19 at 09:02
  • @CertainPerformance You are right again. Thank you for the follow up. If you had a Patreon I would support you :-) – Guy Sep 03 '19 at 09:05
  • I should have done a better research before asking... – Guy Sep 03 '19 at 09:06

0 Answers0