The examples in this article describe the way JavaScript monitors variable changes. Share to everyone for your reference. The specific analysis is as follows:
You should know that in C # for attributes, files, etc. change monitoring is very simple, because there are commissioned (event), FileSystemWatcher and other good dongdong support.
So how do you monitor changes to variables in JavaScript? First, I followed the C # attribute to the JS operation, wrote the following example:
function Class1 ()
{
var oldvalue= ';
var name= ' Xu ';
var id= ' 1 ';
This.setname=function (n)
{
oldvalue=name;
Name=n;
This.propertychange (' name ', oldvalue,n);
}
This.setid=function (n)
{
oldvalue=id;
Id=n;
This.propertychange (' id ', oldvalue,n);
}
This.display=function ()
{
alert (name+ ' \ S ID is: ' +id);
}
}
class1.prototype={
propertychange:function (propertyname,oldvalue,newvalue)
{
alert (propertyname + ' s value changed from ' +oldvalue+ ' to ' +newvalue);
}
;
var c=new Class1 ();
C.setname (' xu22 ');
C.setid (' 5 ');
C.display ();
An assignment operation on an object's internal variable (private variable) is extracted into the method, and the corresponding variable value change callback method is triggered in the method.
It is supposed to be able to monitor variable changes, but on Firefox's official website there is a unwatch called Object.watch, which can be used to monitor variable changes.
Unfortunately, this method does not work properly in browsers such as IE. I searched the internet for a while
Http://stackoverflow.com/questions/1269633/javascript-watch-for-object-properties-changes
Find the following dongdong:
">" > if (! Object.prototype.watch) {Object.prototype.watch = function (prop, handler) {var oldval = This[prop], newval
= Oldval, getter = function () {return newval;
The setter = function (val) {oldval = newval;
return newval = Handler.call (this, prop, Oldval, Val);
}; if (delete This[prop]) {if (Object.defineproperty)//ECMAScript 5 {Object.defineprop
Erty (this, prop, {get:getter,set:setter}); else if (object.prototype.__definegetter__ && object.prototype.__definesetter__) {objec
T.prototype.__definegetter__.call (this, prop, getter);
Object.prototype.__definesetter__.call (this, prop, setter);
}
}
}; } if (!
Object.prototype.unwatch) {Object.prototype.unwatch = function (prop) {var val = This[prop];
Delete This[prop];
This[prop] = val;
}; }
Through __definesetter__ to the assignment operation monitoring ~ ~ ~
OK, good stuff. Collect it.
I hope this article will help you with your JavaScript programming.