有一个 JS Fiddle here , 你能在不克隆到新对象的情况下替换 e.target 吗?
下面重复了那个 fiddle 的听众;
one.addEventListener('click', function(e) {
// default behaviour, don't modify the event at all
logTarget(e);
});
two.addEventListener('click', function(e) {
// replace the value on the same object, which seems to be read-only
e.target = document.createElement('p');
logTarget(e);
});
three.addEventListener('click', function(e) {
function F(target) {
// set another property of the same name on an instance object
// which sits in front of our event
this.target = target;
}
// put the original object behind it on the prototype
F.prototype = e;
logTarget(new F(document.createElement('p')));
});
four.addEventListener('click', function(e) {
// create a new object with the event behind it on the prototype and
// our new value on the instance
logTarget(Object.create(e, {
target: document.createElement('p')
}));
});
最佳答案
我已经更新了你的 fiddle ( http://jsfiddle.net/8AQM9/33/ ),正如你所说,event.target 是只读的,但我们可以用 Object.create
覆盖属性描述符。
您的方法是正确的,但是 Object.create
不仅接收到 key: value
HashMap ,它还接收到 key: property-descriptor
你可以看到at MDN属性描述符是怎样的。
我已经替换了
Object.create(e, {
target: document.createElement('p')
});
与
Object.create(e, {
target: {
value: document.createElement('p')
}
});
这将原型(prototype)化 e
并修改新对象的 target
属性。
关于javascript - 在 JavaScript 事件中替换/覆盖/覆盖 e.target,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14874045/