Listening for variable changes in JavaScript

后端 未结 22 3271
自闭症患者
自闭症患者 2020-11-21 06:57

Is it possible to have an event in JS that fires when the value of a certain variable changes? JQuery is accepted.

22条回答
  •  轮回少年
    2020-11-21 07:25

    In my case, I was trying to find out if any library I was including in my project was redefining my window.player. So, at the begining of my code, I just did:

    Object.defineProperty(window, 'player', {
      get: () => this._player,
      set: v => {
        console.log('window.player has been redefined!');
        this._player = v;
      }
    });
    

提交回复
热议问题