Javascript Track Variable Change

2019-08-01 08:09发布

问题:

Is it possible to track a variable change in javascript? I would like to be able to launch a function when a variable has been changed in a class.

<script>
var mywindow = new Box();
mywindow.title = "newtitle"; 
//Launches mywindow.applyTitle() and changes html
</script>

回答1:

You could probably use an explicit method for setting the value and attach your callbacks to that. Something along this would work:

var Box = new Class({
    setTitle: function(title) {
        this.title = title;

        // call your callbacks now. you probably need some way to register them btw
    }
});

Adapt the idea to fit your class syntax...

There is also a not so well supported getter/setter syntax for JS (equivalent to properties in Python). See http://ejohn.org/blog/javascript-getters-and-setters/ .



回答2:

Not automatically. Probably best would be to add to the prototype of the Box class with a setter function that you can use instead of setting the property directly.

Example: http://jsfiddle.net/PEYyk/

var Box = function() {
    // the constructor
};
Box.prototype.setTitle = function( new_title ) {
    this.title = new_title;
    this.applyTitle();
};
Box.prototype.applyTitle = function() {
    // apply the title
};

Then call it like this:

var mywindow = new Box();
mywindow.setTitle( "newtitle" );