在javascript中,是否可以在函数属性从
更改时创建事件处理程序window.onclick = function() { ....function 1...... };
到
window.onclick = function() { ....function 2..... };
答案 0 :(得分:7)
这已经有几年了,但对我来说效果很好。几年前,SO用户发布了一个开源对象观察者。它会修改对象原型,以便您监视对象的特定属性的更改。
window.watch('onclick', function() { console.log('changed'); });
window.onclick = function() { console.log('click1'); };
window.onclick = function() { console.log('click2'); };
JSFiddle:https://jsfiddle.net/gou48xpa/
源代码:https://gist.github.com/eligrey/384583(随MIT许可证一起发布)
if (!Object.prototype.watch) {
Object.defineProperty(Object.prototype, "watch", {
enumerable: false
, configurable: true
, writable: false
, value: 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
Object.defineProperty(this, prop, {
get: getter
, set: setter
, enumerable: true
, configurable: true
});
}
}
});
}
// object.unwatch
if (!Object.prototype.unwatch) {
Object.defineProperty(Object.prototype, "unwatch", {
enumerable: false
, configurable: true
, writable: false
, value: function (prop) {
var val = this[prop];
delete this[prop]; // remove accessors
this[prop] = val;
}
});
}
答案 1 :(得分:0)
使用addEventlistener
或attachEvent
element.attachEvent('onclick', handler);
或
element.addEventlistener('onclick', handler, false)
你可以把它包装成某个功能