What does the param mean in SAEF?

I'm newbie in javascript.I ever read the article with the SAEF,while i still have question, the code is below:

var addEvent = (function( window, document ) {
    if ( document.addEventListener ) {
        return function ( elem, type, callback ) {
            //if elem exist and is a single node.
            if ( elem && !elem.length || elem === window ) { 
                elem.addEventListener( type, callback, false );
            } else if ( elem && elem.length ) { //elem is an node of array
                for ( var i = 0; i < elem.length; i++ ) {
                    addEvent( elem[i], type, callback );
                }
            }
        }
    } else if ( document.attachEvent ) {
        return function ( elem, type, callback ) {
            //if elem exist and is a single node
            if ( elem && !elem.length || elem === window ) { 
                elem.attachEvent( 'on'+type, 
                    function () {
                        callback.call( elem, window.event );
                } );
            } else if ( elem && elem.length ){
                for ( var i = 0; i < elem.length; i++ ) {
                    addEvent( elem[i], type, callback );
                }
            }
        }
    }
})( this, document );
    
My question is what does the param this and document mean for?Are both of them the real param that will replace the param of window and document which are contained within the Anonymous function?


This is a JavaScript pattern known as an immediate function. It takes the form:

 (function(param1, param2, ...) {
    /* ...  function body  ... */
 }(var1, var2));

You are correct that it involves the creation of an anonymous function and then calls it with a set of variables.

It allows developers to create a scope from which no variables leak. JavaScript only has Global and Function scope. Any variables declared outside of a function body are automatically in the Global scope.

Immediate functions avoid that problem.

In this case, as in many cases, the immediate function will return something that contains some of the inner variables inside a closure. This protects them, but makes their values available in a protected way.

In this case, you're returning a function that will allow callers to add an event to an HTML Element. You'll commonly see immediate functions being used to create cross-browser methods. The call to the immediate function will do all of the browser method sniffing and then generate the appropriate cross-browser method. This means that the sniffing is done once and once only. This saves you from sniffing the browser every time you call the method.

链接地址: http://www.djcxy.com/p/71136.html

上一篇: 你能在iPad上自动播放HTML5视频吗?

下一篇: 参数在SAEF中意味着什么?