StoryCode

자바스크립트.변수.모니터링워처

JavaScript, ECMAScript
반응형

function print(t) {
  var c = document.getElementById('console');
  c.innerHTML = c.innerHTML + '
' + t;
}

// Demo
var varw = (function (context) {
  return function (varName, varValue) {
    var value = varValue;
  
    Object.defineProperty(context, varName, {
      get: function () { return value; },
      set: function (v) {
        value = v;
        print('Value changed! New value: ' + value);
      }
    });
  };
})(window);

varw('varWatch'); // Declare
print(varWatch);
varWatch = 456;
print(varWatch);

print('---');

varw('otherVarWatch', 123); // Declare with initial value
print(otherVarWatch);
otherVarWatch = 789;
print(otherVarWatch);

 

 

결과)

undefined
Value changed! New value: 456
456
---
123
Value changed! New value: 789
789

 

참조) https://stackoverflow.com/questions/1759987/listening-for-variable-changes-in-javascript

반응형

'JavaScript, ECMAScript' 카테고리의 다른 글

자바스크립트 역사.  (0) 2020.09.21
Count, 카운트  (0) 2020.03.09
실수를 정수로 바꾸는 방법  (0) 2020.03.04
Hoisting.호이스팅  (0) 2020.02.12
한글 받침 구별법  (0) 2019.04.15