7

这里有一个JS Fiddle,你可以在不克隆到新对象的情况下替换 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')
  }));
});
4

1 回答 1

3

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

您的方法是正确的,但Object.create不仅接收key: value哈希图,它还接收key: property-descriptor您可以在 MDN上看到属性描述符的情况。

我已经换了

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

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

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

于 2013-04-11T14:12:26.907 回答