search

Home  >  Q&A  >  body text

javascript - Questions about the compatible writing methods of addEventListener and attachEvent, please help!

The first way of writing

里面的if分支只会执行一次,返回的函数里面已经不包含浏览器判断了,所以相对于常规写法,已经很棒了
var addEvent = (function(){
    if(window.addEventListener){
        return function(elem, type, handler){
            elem.addEventListener(type, handler, false);
        };
    }else if(window.attachEvent){
        return function(elem, type, handler){
            elem.attachEvent('on' + type, handler)
        };
    }
})();

The second way of writing

在第一次进入if判断后,重写了addEvent函数,这样后续的addEvent也不包含分支判断语句了,感觉跟第一种写法并没有多大的区别,但是第二种写法被称为惰性载入函数,可是我并没有感觉他比第一种方式惰在哪里啊?相较来说,我更喜欢第一种方式,求解释
var addEvent = function(elem, type, handler){
    if(window.addEventListener){
        addEvent = function(elem, type, handler){
            elem.addEventListener(type, handler, false);
        };
    }else if(window.attachEvent){
        addEvent = function(elem, type, handler){
            elem.attachEvent('on' + type, handler);
        };
    }

    addEvent(elem, type, handler);
};

It’s very clear, thank you!

Samhanx

PHPzPHPz2755 days ago736

reply all(3)I'll reply

  • 给我你的怀抱

    给我你的怀抱2017-05-16 13:41:30

    Pay attention to the IIFE in the first way of writing, so that when the code is executed and the addEvent function is assigned, it will be clear whether addEvent is a function returned by if or else if.

    In the second way of writing, addEvent is still the outermost function when executing the code. When you actually call addEvent(), you reassign the value internally to clarify what addEvent is, and then call itself within the function. This is where laziness lies. Bar.

    Note that there is a passing process for the intermediate parameters, and if it is not called, the reference to the outer function will always be saved on addEvent. After the immediate execution function of the first way of writing is executed, the memory occupied by the anonymous function has been Start waiting for recycling.

    reply
    0
  • 黄舟

    黄舟2017-05-16 13:41:30

    I understand that the second method is called a lazy loading function, which is relative to the first method:
    1) The first method, because it is an IIFE, regardless of whether addEvent is called or not It has been confirmed that the browser supports addEventListener or attachEvent; addEvent, 都已经确认了浏览器支持的是addEventListener ,还是attachEvent
    2) 第二种方法,则是在显式调用addEvent 2) The second method is when explicitly calling addEvent To know the browser support status.

    reply
    0
  • 漂亮男人

    漂亮男人2017-05-16 13:41:30

    In the second method, addEvent has been reassigned after the first call, and there is no need to perform branch judgment on the second call

    reply
    0
  • Cancelreply