最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

object - ReplaceOverrideOverwrite e.target in a JavaScript Event - Stack Overflow

programmeradmin0浏览0评论

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

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')
  }));
});
Share Improve this question asked Feb 14, 2013 at 11:41 Jamie MasonJamie Mason 4,2112 gold badges34 silver badges42 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 3

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

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.

I've replaced

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

With

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

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

发布评论

评论列表(0)

  1. 暂无评论