Firefoxには、それぞれの特定のプロパティが変更されたときにイベントをトリガーするために必要ないくつかのオブジェクトがあります。object.watch()を使用していますが、「this」を使用して変更されたプロパティの値を返すと、最初は古い値を返し、2回目以降は「undefined」を返します。
var myObject = {
"aProperty": 1
};
function propChanged(prop) {
alert(prop);
}
myObject.watch("aProperty", function () {
propChanged(this.aProperty);
});
myObject.aProperty = 2;//alerts "1"
myObject.aProperty = 3;//alerts "undefined"
alert(myObject.aProperty)とだけ言えないのは、これがイベントハンドラーをいくつかの、場合によっては未知のオブジェクトに適用する動的コードであることが意図されているためです。
watchメソッドを使用してプロパティの新しい値を動的に取得する方法が正確にわかりません。このためにIEのプロトタイプを設定しているので、そこで機能しないことを心配していません。「これ」と、それがウォッチメソッドの所有者にどのように適用されるかを理解する必要があります。
編集>>
IEなどのプロトタイプを含むクロスブラウザに使用している新しいコードは次のとおりです。
var myObject = {};
if (!Object.prototype.watch) {
Object.prototype.watch = 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
if (Object.defineProperty) // ECMAScript 5
Object.defineProperty(this, prop, {
get: getter,
set: setter
});
else if (Object.prototype.__defineGetter__ && Object.prototype.__defineSetter__) { // legacy
Object.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]; // remove accessors
this[prop] = val;
};
}
function propChanged(t, p, o, n) {
alert(o);
}
Object.defineProperty(myObject, "aProperty", {value: 2,
writable: true,
enumerable: true,
configurable: true});
myObject.watch("aProperty", propChanged);
myObject.aProperty = 3; //alerts 3
myObject.aProperty = 4; //alerts 4 (n is undefined in propChanged?