Replace / override / overwrite e.target in JavaScript event

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

Then the listeners of this violin 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') })); }); 
+6
source share
1 answer

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

You were on the right track, but Object.create does not extract only the hash of the key: value file, it returns key: property-descriptor , you can see in MDN as a property descriptor.

I replaced

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

WITH

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

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

+4
source

All Articles