在JavaScript事件中替换/覆盖/覆盖e.target

Jam*_*son 6 javascript prototype object mouseevent

这里有一个JS小提琴,你可以在不克隆到新对象的情况下替换e.target吗?

来自那个小提琴的听众在下面重复;

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')
  }));
});
Run Code Online (Sandbox Code Playgroud)

A. *_*ada 3

我已经更新了你的小提琴(http://jsfiddle.net/8AQM9/33/),正如你所说,event.target是只读的,但我们可以用Object.create.

你的方法是正确的,但Object.create不仅仅接收到了key: valuehashmap,它还接收到了key: property-descriptor你可以在 MDN 上看到的属性描述符是怎样的。

我已经更换了

Object.create(e, {
    target: document.createElement('p')
});
Run Code Online (Sandbox Code Playgroud)

Object.create(e, {
    target: {
        value: document.createElement('p')
    }
});
Run Code Online (Sandbox Code Playgroud)

这将创建新对象的原型e并修改其属性。target

  • 在 Chrome 51 中不起作用。除新事件对象的目标之外的所有属性均显示为“[异常:TypeError:MouseEvent.remoteFunction 处的非法调用 (<anonymous>:3:14)]” (4认同)
  • 请参阅 /sf/ask/881512481/ 以获取正确的解决方案。 (2认同)