想了解更多关于未定义的信息 [英] Want To Know More About Undefined

查看:43
本文介绍了想了解更多关于未定义的信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如您所见,undefined 不是 javascript 中的关键字(对吗?)所以我们可以将它用作变量,尽管我确定这是一个坏主意.现在我的问题是为什么我不能给出一个未定义的值.

As you see,undefined is not a keyword in javascript(Is it right?).So we can use it as a variable though I'm sure this is a bad idea.Now my question is why I can't give a value to undefined.

代码:

var undefined=3;

undefined;//still undefined  

任何建议将不胜感激.

推荐答案

因为在较旧的环境中(JS 1.8.5 之前)可以更改 undefined 的值,并且检查不存在的东西是在一种可以打破的方式.在他们自己的闭包中开发库是一种常见的选择,使用 IIFE 模式创建一个变量 undefined,它不受外部代码(例如 jQuery 和大多数库)的影响,这是一个例子:

Because in older environments(before JS 1.8.5) it was possible to change the value of undefined, and checking for something that didn't exist was made in a way that was possible to break. It is a common choice to develop libraries inside their own closures, using the IIFE pattern to create a variable undefined which is not touched from external code(jQuery for example, and most libraries), this is an example:

(function(undefined) {
    //code which safely uses undefined
})();

请注意,有一个名为 undefined 的参数,并且 没有任何参数 调用了 IIFE,使得 undefined 有效地变为 undefined.在较新的环境中,无法更改 undefined 的值,但为了向后兼容,它还被大量使用.

Note that there is a parameter called undefined and the IIFE is invoked without any parameter, making that undefined effectively become undefined. In newer environments it is not possible to change the value of undefined, but for retrocompatibility it is yet used a lot.

然而,检查未定义类型的最安全方法是使用 typeof.它的用法,事实上,不能以任何方式被覆盖,它可以安全地使用:typeof foo == 'undefined'.

Yet the safest way to check for an undefined type is to use typeof. Its usage, in fact, cannot be overridden in any way, and it can be used safely: typeof foo == 'undefined'.

请记住,未定义未声明之间存在细微差别:

Remember that there is a slight difference between undefined and undeclared:

var x; //declared but undefined
x === undefined; //true

但在较旧的环境中您可以这样做

But in older environments you were able to do

var undefined = 1;
var x; //declared, of type undefined, but...
x === undefined // false, because undefined is 1 and x is of type undefined

正如我之前所说,检查未定义变量的最安全方法(确保它可以在较旧的环境中工作)是使用 typeof:

As I said before, the safest way to check for an undefined variable(being sure it will work in older environments) is to use typeof:

var undefined = 1;
var x;
typeof x == 'undefined'; //true

还请记住,使用带有 undefined 的等式检查 (==) 也会检查 null(实际上,undefined ==nullundefined !== null),所以我推荐使用严格相等操作符(===),它检查只针对 未定义.

Remember also that using equality check(==) with undefined also checks for null(in fact, undefined == null but undefined !== null), so I recommend using strictly equality operator(===), which checks only for undefined.

这篇关于想了解更多关于未定义的信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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