克隆javascript事件对象

问题描述:

有人知道如何对本地javascript事件对象进行深层复制/克隆吗?我知道我可以创建一个新的事件对象并手动设置适当的属性以匹配原始事件,但是如果有一种方法可以克隆,那就容易得多。

Anybody know how to do a deep copy/cloning of a native javascript event object? I know I can create a new event object and set the appropriate properties manually to match the original event, but it'd be much easier if there's a way to just clone.

出于您的目的,我只是将其作为新对象构造函数的原型,并覆盖要更改的对象。由于循环引用问题,JS的克隆变得混乱,因此它可能不是您所希望的快速而肮脏的解决方案。

For your purposes I'd just make it a prototype of a new object constructor and override the ones you want changed. Cloning in JS gets messy due to the circular reference issue so it may not be the quick and dirty solution you were hoping for.

function cloneEventObj(eventObj, overrideObj){

   if(!overrideObj){ overrideObj = {}; }

   function EventCloneFactory(overProps){
       for(var x in overProps){
           this[x] = overProps[x];
       }
    }

    EventCloneFactory.prototype = eventObj;

    return new EventCloneFactory(overrideObj);

}

//So add your override properties via an object
$el.click(function(e){
    var newEventObj = cloneEventObj(
        e,
        { target:document.body }
    );
    doSomething(newEventObj);
});

//or just stick 'em on manually after spitting the object out
/*...
var newEventObj = cloneEventObj(e);
newEventObj.target = document.body
...*/

在在这种情况下,克隆对象是新对象的原型对象。在原型对象之前检查 this。属性,以便覆盖这些属性。或者,您也可以在对象建立后附加属性。

In this case the 'cloned' object is the prototype object of the new object. 'this.' properties are checked for before the prototype object so these will override. Or you could just attach properties after the object is built.