下一个参数是'undefined'在jQuery中,为什么

Next parameter is 'undefined' in jQuery, why?

本文关键字:为什么 jQuery 参数 下一个 undefined      更新时间:2023-09-26

jQuery的代码中,为什么下一个参数是undefined

JavaScript:

(function(a,b){
    ....
})(window)

这里是a=window而不是b=undefined,为什么是这样?

这是一种常见的技术,以确保您有一个真正的undefined值来检查,因为窗口对象的undefined属性过去是可写的,因此不能可靠地用于检查。由于只向函数传递了一个参数,因此第二个参数确保undefined。该变量的名称无关紧要,它可以是undefined,也可以是foobar,或者像本例中一样,b(因为这是节省宝贵字节的最短方法)。

现在您可以安全地检查变量的未定义,因为您确定b的值:

// overwriting the global undefined property works in old browsers
undefined = 3;
(function(a,b){
    var asd; // not initialised, thus undefined
    if (asd === undefined){
       // should trigger, but won't because undefined has been overwritten to 3
    }
    if (asd === b){
       // is safe, bcause you know that b is undefined
    }
})(window)

新浏览器(IE9, FF4+, Chrome)遵守EcmaScript5规范,undefined不再是可写的

因为您没有为第二个参数传递任何内容。你只经过一个,即window

代码

(function(a,b){
    ....
})(window)

定义一个函数并立即调用它。上面的最后一行实际上使用window参数调用函数。如果你在那里传递了2个参数,b将不是未定义的

这是你试图使用的即时javascript函数语法:

(/* function body */)(/* params */)

命名函数定义如下:

function addNumbers(a, b){
    alert(a + b);
}

你叫它:

addNumbers(1, 2)

或类似的即时函数(同时定义和执行):

(function(a, b){
    alert(a + b);
})(1, 2)