Para las variables locales, la comprobación con localVar === undefined
funcionará porque deben haberse definido en algún lugar dentro del alcance local o no se considerarán locales.
para variables que no son locales y no se definen en cualquier lugar, el cheque someVar === undefined
lanzará una excepción: ReferenceError no detectada: j no está definido
Aquí hay un código que permitirá aclarar lo que estoy diciendo anteriormente. Preste atención a los comentarios en línea para mayor claridad.
function f (x) {
if (x === undefined) console.log('x is undefined [x === undefined].');
else console.log('x is not undefined [x === undefined.]');
if (typeof(x) === 'undefined') console.log('x is undefined [typeof(x) === \'undefined\'].');
else console.log('x is not undefined [typeof(x) === \'undefined\'].');
// This will throw exception because what the hell is j? It is nowhere to be found.
try
{
if (j === undefined) console.log('j is undefined [j === undefined].');
else console.log('j is not undefined [j === undefined].');
}
catch(e){console.log('Error!!! Cannot use [j === undefined] because j is nowhere to be found in our source code.');}
// However this will not throw exception
if (typeof j === 'undefined') console.log('j is undefined (typeof(x) === \'undefined\'). We can use this check even though j is nowhere to be found in our source code and it will not throw.');
else console.log('j is not undefined [typeof(x) === \'undefined\'].');
};
Si llamamos el código anterior como esto:
f();
La salida sería la siguiente:
x is undefined [x === undefined].
x is undefined [typeof(x) === 'undefined'].
Error!!! Cannot use [j === undefined] because j is nowhere to be found in our source code.
j is undefined (typeof(x) === 'undefined'). We can use this check even though j is nowhere to be found in our source code and it will not throw.
Si llamamos el código anterior como éstos (con cualquier valor en realidad) :
f(null);
f(1);
La salida serán los siguientes:
x is not undefined [x === undefined].
x is not undefined [typeof(x) === 'undefined'].
Error!!! Cannot use [j === undefined] because j is nowhere to be found in our source code.
j is undefined (typeof(x) === 'undefined'). We can use this check even though j is nowhere to be found in our source code and it will not throw.
Al hacer el registro de entrada como esta: typeof x === 'undefined'
, que está pidiendo esencialmente esto: Por favor, compruebe si la variable x
existe (se ha definido) en alguna parte del código fuente. (más o menos). Si conoce C# o Java, este tipo de comprobación nunca se realiza porque, si no existe, no se compilará.
<== Fiddle Me ==>
No puedo responder a la pregunta de por qué jQuery usaría ambos enfoques, pero JavaScript tiene algunas peculiaridades interesantes que significan estas dos cosas son sutilmente diferentes.No debería importar la mayor parte del tiempo (es decir, si su código es sensato), pero hay diferencias, sin embargo: consulte aquí para una reseña - http://wtfjs.com/2010/02/15/undefined-is- mutable – Spudley
Como señaló @Struppi, la función más externa de jQuery tiene un argumento llamado indefinido. Dentro de jQuery, 'foo === undefined' se compara con la copia local de indefinido en lugar de global (window.undefined), que puede haber sido modificado por código demente. El hecho de que undefined sea mutable es definitivamente digno de mención y me alegra que lo hayas hecho. (+1) –