属性监听器
在Proxy没有标准化之前,FF的Object.prototype.watch可是一个好东西。通过ecma262v5的特性描述符,我们可以实现此功能,这用于node.js最好不过了。
if ( ! Object.prototype.watch) {
Object.defineProperty(Object.prototype, 'watch', {
value: function (prop, handler) {
var val = this[prop];
var getter = function () {
return val;
};
var setter = function (newVal) {
var val = handler.call(this, prop, val, newVal);
};
if (delete (this[prop])) {
Object.defineProperty(this, prop, {
get: getter,
set: setter,
configurable: true
});
}
}
});
}
/**
* Object.unwatch() - Removes a watchpoint set with the watch method.
* @param prop
*/
if ( ! Object.prototype.unwatch) {
Object.defineProperty(Object.prototype, 'unwatch', {
value: function (prop) {
var val = this[prop];
delete (this[prop]);
this[prop] = val;
}
});
}
机器瞎学/数据掩埋/模式混淆/人工智障/深度遗忘/神经掉线/计算机幻觉/专注单身二十五年
浙公网安备 33010602011771号