在JavaScript事件中替换/覆盖/覆盖e.target [英] Replace/Override/Overwrite e.target in a JavaScript Event

查看:78
本文介绍了在JavaScript事件中替换/覆盖/覆盖e.target的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

There's a JS Fiddle here, can you replace e.target without cloning to a new object?

下面重复该小提琴的听众;

The listeners from that fiddle are repeated below;

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')
  }));
});


推荐答案

我已经更新了你的小提琴( http://jsfiddle.net/8AQM9/33/ ),正如你所说,event.target是readonly,但是我们可以用 Object.create 覆盖属性描述符。

I've updated your fiddle (http://jsfiddle.net/8AQM9/33/), as you said, event.target is readonly, but we can overwrite the property descriptor with Object.create.

你是在正确的方式,但 Object.create 不仅仅重新获取键:value hashmap,它重现 key:property-descriptor 您可以在MDN上看到 属性描述符是如何的。

You were on the right way but Object.create does not recive only the key: value hashmap, it recives key: property-descriptor you can see at MDN how a property descriptor is.

我已经替换了

Object.create(e, {
    target: document.createElement('p')
});

使用

Object.create(e, {
    target: {
        value: document.createElement('p')
    }
});

这将原型 e 并修改目标新对象的属性。

And this will prototype e and modify the target property of the new object.

这篇关于在JavaScript事件中替换/覆盖/覆盖e.target的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆