LoginSignup
1
0

More than 5 years have passed since last update.

Javascriptでグローバル変数への値の代入を検知する

Last updated at Posted at 2018-12-01

GetterとSetterを使う。JavascriptのバージョンはES2015。

windowオブジェクトにプロパティを追加

例として、xというグローバル変数の値を監視する。プロパティの追加はObject.definePropertyを使う。

Object.defineProperty(window,'x', {
    configurable: false,
    val: undefined,
    get: function () { return this.val; },
    set: function (x) {
        this.val = x;
        console.log( x+' was assigned to x');
    },
});

getterを定義し忘れると、値を参照できなくなるので注意。
代入時に任意の処理を行いたいときは、console.log( x+' was assigned to x'); 部分を書き換える。

処理

x = 1;
x = 2;

結果

1 was assigned to x
2 was assigned to x
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0