Q:

Background function javascript

I work with javascript. Let's suppose I have the following function in my app:
function verify(cats) {
  if ( cats > 20 ) {
    // do something
  }
}

Supposing i have a button to add cats, I may use that function after every cat adding.
However, i don't like this method.
I want that this function be in the background and is executed automatically when the condition states true
Is there some way to do so ?

A:

Use a setter, that runs on every assignment. Before:
var obj = {};
obj.cats = 10;
obj.cats += 30;
verify(obj.cats); // we don't want to call this each time.

After:
var obj = {
    _cats : 0, // private
    get cats() { return this._cats; },
    set cats(num) {
        verify(num); // any verification here
        this._cats = num;
    }
};

Later, you can do:
obj.cats += 10; // will run verification
obj.cats = 15; // same

Alternatively, you can use a proxy, but those aren't really widely supported by JS engines yet.

