자바스크립트.변수.모니터링워처
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