jQuery代码中的未定义变量 [英] undefined variable in jquery code

查看:197
本文介绍了jQuery代码中的未定义变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几天前,我问了一个有关javascript中未定义值的问题. (比较值的最佳方法是什么反对未定义"?) 我得出结论,因为!== undefined可以设置为另一个"值,所以执行!== undefined是一个不好的做法.

I asked a question about the undefined value in javascript a few days ago. (What is the best way to compare a value against 'undefined'?) I conclude that it is a bad practice to do !== undefined as undefined can be set to 'another' value.

undefined='foo';
var b;
(b !== undefined) // true

我快速浏览了一下jquery代码,我意识到作者在每个部分都使用!== undefined而不是typeof var !== "undefined"

I gave a quick look at the jquery code, I realized that in every part, the author use !== undefined and not typeof var !== "undefined"

// Setting one attribute
if ( value !== undefined ) {
// Optionally, function values get executed if exec is true
    exec = !pass && exec && jQuery.isFunction(value);

这可能是错误吗?即使我知道我们应该为重新分配undefined的值而疯狂-对于最受欢迎的库,我认为它可能会导致一些错误...

Is it a possible mistake? Even if I know that we should be crazy to reassign the value of undefined - for the most popular library I think it can cause some mistakes...

谁做对了?

推荐答案

undefined实际上是包装整个代码的函数的未定义参数:

undefined in the jQuery code is actually an undefined parameter of a function wrapping the whole code:

(function(window, undefined) {
    // jQuery code here
    // undefined is the undefined parameter
}(window)); // notice we don't pass a second argument here

这是非常安全的,因为undefined参数是该函数的局部变量,并且除该函数中的代码外,没有其他人可以为其赋值.

That's perfectly safe, as the undefined parameter is local to the function, and nobody except the code in this function can assign to it.

使用更清晰的语法:

var myFunc = function(window, undefined) {
    // jQuery code here

    // The undefined variable is the undefined parameter

    // If the function has been called without a second argument,
    // then the undefined parameter is undefined.
};
myFunc(window); // no second argument

这篇关于jQuery代码中的未定义变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆