var undefined = true; [英] var undefined = true;

查看:67
本文介绍了var undefined = true;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用这种恶意JavaScript行: var undefined = true;

I'm doing some experimenting with this malicious JavaScript line: var undefined = true;

每个未初始化JavaScript中的变量具有 undefined 的值,它只是一个保存'undefined'的特殊值的变量,所以以下应执行警告

Every uninitialized variable in JavaScript has the value of undefined which is just a variable that holds the special value of 'undefined', so the following should execute the alert:

var undefined = true, 
    x;

if (x) {
    alert('ok');
}

但事实并非如此,我的问题是为什么?

But it doesn't, and my question is why?

在进一步的实验中,我尝试了以下内容:

On further experimentation, I tried the following:

var undefined = true, 
    x = undefined;

if (x) {
    alert('ok');
}

这次,提醒已执行。

所以我的问题是......因为在第一个片段中 x 持有 undefined (因为它没有初始化),为什么 alert 没有执行?奇怪的是,当明确声明 x undefined x = undefined ),警告执行...

So my question is...since in the first snippet x holds undefined (because it is not initialized), why didn't the alert execute? The strange thing is that when explicitly stating that x is undefined (x = undefined), the alert executed...

推荐答案

名为 undefined 的变量与名为 undefined 的值之间存在差异。

There is a difference between a variable named undefined and the value called undefined.

var undefined = true, 
    x;

在此示例中,变量 undefined 是设置为值 true ,并将 x 设置为值(不是变量!) undefined

In this example, the variable undefined is set to the value true, and x to the value (not the variable!) undefined.

var undefined = true, 
    x = undefined;

在此示例中,变量 undefined 是设置为值 true x 设置为变量 undefined ( true )。

In this example, the variable undefined is set to the value true as well, and x is set to the value contained in the variable undefined (which is true).

所以,虽然你可以声明一个名为 undefined 的变量,您无法更改非初始化变量设置为值 undefined 的事实。

So, while you can declare a variable named undefined, you cannot change the fact that non-initialized variables are set to the value undefined.

这篇关于var undefined = true;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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