考虑到那些javascript代码,缓存event.target有好处吗?我使用这种事件来避免在竞争者中附加数千个事件侦听器。

我应该这样做:

$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
        }

    });

最佳答案

是的,确实有道理。变量比属性查找要快。不,你应该做

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

09-25 17:31