2013-02-14 19 views
6

Istnieje JS Fiddle here, czy można zastąpić e.target bez klonowania do nowego obiektu?Zastąpienie/Zastąpienie/Zastąpienie e.target w zdarzeniu JavaScript

Słuchacze z tego skrzypka powtarza się poniżej;

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

Odpowiedz

4

mam zaktualizowane skrzypce (http://jsfiddle.net/8AQM9/33/), jak pan powiedział, event.target jest tylko do odczytu, ale możemy zastąpić deskryptor działce z Object.create.

Byłaś na dobrej drodze, ale Object.create nie recive tylko key: value hashmap, to recives key: property-descriptor widać at MDN jak deskryptor nieruchomość.

mam wymienić

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

Z

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

A to prototyp e i modyfikować właściwości nowego obiektu target.

+0

Świetna robota, dziękuję! –

+1

Nie działa w przeglądarce Chrome 51. Wszystkie właściwości oprócz obiektu docelowego nowego obiektu zdarzenia są następujące: [[Exception: TypeError: Illegal invocation at MouseEvent.remoteFunction (: 3: 14)] ' –

Powiązane problemy