缓存event.target是否有意义?

时间:2014-06-07 11:11:55

标签: javascript performance caching delegation

考虑到javascript代码,缓存event.target是否有优势?我使用这种事件来避免在竞争对手中附加数千名eventlistener。

我应该这样做:

$element.addEventListener("click",function(event)
{

    if(event.target.id == "someid" )
    {
        event.target.dosomething
        event.target.dosomething
        event.target.dosomething
        event.target.dosomething
    }
    else if (event.target.id == "someanotherid" )
    {
        event.target.dosomething
        event.target.dosomething
        event.target.dosomething
        event.target.dosomething
    }

});

或者这个:

$element.addEventListener("click",function(event)
    {

        if(event.target.id == "someid" )
        {
          var targetA = event.target;

            targetA.dosomething
            targetA.dosomething
            targetA.dosomething
            targetA.dosomething
        }
        else if (event.target.id == "someanotherid" )
        {
          var targetB = event.target;

            targetB.dosomething
            targetB.dosomething
            targetB.dosomething
            targetB.dosomething
        }

    });

1 个答案:

答案 0 :(得分:1)

是的,它确实有意义。变量比属性查找更快。不,你应该做

$element.addEventListener("click", function(event) {
    var target = event.target;
    if (target.id == "someid") {
        target.dosomething1
        target.dosomething2
        target.dosomething3
        target.dosomething4
    } else if (target.id == "someanotherid") {
        target.dosomethingelse1
        target.dosomethingelse2
        target.dosomethingelse3
        target.dosomethingelse4
    }
});