克隆javascript事件对象 [英] cloning javascript event object

查看:78
本文介绍了克隆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.

这篇关于克隆javascript事件对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆