The following four methods will work depending on support by browser compatibility, and this post did take me a while, but it also taught me what ___
does, and I hope I listed most methods, and if you know more, you could post an answer. However, it would be greatful of you to post your method in the comments so I can add it to this answer. Cheers!
1 Use Object.observe:
Object.observe(i, function(b){ b.object[change.name] > b.type ? console.log('decreased') : console.log('increased'); });
Additional notes about Object.observe
If you like to enable it in Chrome 33,
Visit chrome://flags/
And enable Enable Experimental JavaScript
2 Use setInterval:
var i = 4;
var a = i;
setInterval(function()
{
if(i != a) a > i ? console.log('decreased') : console.log('increased');
}, 1000);
i = 10;
should log 'increase' in one second.
3 Use Object.watch:
var i = {i:5};
i.watch("i", function (id, oldval, newval) {
newval > oldval ? console.log('decreased') : console.log('increased');
return newval;
});
Additional notes about Object.watch
To support more browsers, add this script:
if (!Object.prototype.watch) {
Object.defineProperty(Object.prototype, "watch", {
enumerable: false
, configurable: true
, writable: false
, value: function (prop, handler) {
var
oldval = this[prop]
, newval = oldval
, getter = function () {
return newval;
}
, setter = function (val) {
oldval = newval;
return newval = handler.call(this, prop, oldval, val);
}
;
if (delete this[prop]) { // can't watch constants
Object.defineProperty(this, prop, {
get: getter
, set: setter
, enumerable: true
, configurable: true
});
}
}
});
}
// object.unwatch
if (!Object.prototype.unwatch) {
Object.defineProperty(Object.prototype, "unwatch", {
enumerable: false
, configurable: true
, writable: false
, value: function (prop) {
var val = this[prop];
delete this[prop]; // remove accessors
this[prop] = val;
}
});
}
obtained from https://gist.github.com/eligrey/384583
4. Use a custom value set function:
i = 4;
function setValue(obj, val)
{
val < obj ? console.log('decrease') : console.log('increase');
obj = val;
}
setValue(i, 10);
should log 'increase'.
Most of these require the variable to be an Object, so I'd rather detect over time as seen in method 2.