2013-02-14 66 views
6

में e.target को बदलें/ओवरराइड/ओवरराइट करें JS Fiddle here है, क्या आप 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

मैं, अपने बेला (http://jsfiddle.net/8AQM9/33/) को नवीनीकृत किया है के रूप में आप ने कहा, event.target केवल पढ़ने के लिए है, लेकिन हम Object.create साथ संपत्ति वर्णनकर्ता के ऊपर लिख सकते हैं।

आप सही रास्ते पर थे, लेकिन Object.create केवल key: value hashmap recive नहीं है, यह key: property-descriptor recives आप at MDN देख सकते हैं कि एक संपत्ति की जानकारी देता है।

मैं

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

बदल दिया है साथ

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

और यह e प्रोटोटाइप और नई वस्तु की target संपत्ति को संशोधित करेगा।

+0

ग्रेट वर्क, धन्यवाद! –

+1

क्रोम 51 में काम नहीं करता है। नए इवेंट ऑब्जेक्ट के लक्ष्य को छोड़कर सभी गुणों को पढ़ा जाता है '[अपवाद: टाइप एरर: MouseEvent.remoteFunction पर अवैध आमंत्रण (: 3: 14)] ' –