为什么我的JavaScript提升局部变量返回undefined但是提升的全局变量返回空白? [英] Why is my JavaScript hoisted local variable returning undefined but the hoisted global variable is returning blank?

查看:129
本文介绍了为什么我的JavaScript提升局部变量返回undefined但是提升的全局变量返回空白?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为我学习JavaScript的一部分,我尝试编写代码来演示我正在学习的概念;今天我正在学习悬挂变量。这是我写的代码:

As part of my learning JavaScript, I try to write code to demonstrate the concept I am learning; today I'm learning hoisted variables. Here is the code I wrote:

console.log("A: My name is " + name);   

function happy() {
  console.log ("1: I am " + feeling);   
    var feeling = "happy";
  console.log ("2: I am " + feeling);   
}
happy(); 

var name = "Jim";
console.log("B: My name is " + name);   

我预计会有以下结果:

A: My name is undefined
1: I am undefined
2: I am happy
B: My name is Jim

但是,在WriteCodeOnline.com和另一个沙箱中测试我的代码时,第一个console.log显示答:我的名字是。我正在使用Chrome浏览器,如果这有所不同。

However, when testing my code at WriteCodeOnline.com and in another sandbox, the first console.log displays A: My name is. I am using a Chrome browser, if that makes a difference.

所以,我的问题是,为什么函数中提升的局部变量在提升的全局变量时返回undefined返回空白?

So, my question is, why does the hoisted local variable within the function return undefined while the hoisted global variable returns a blank?

推荐答案

这里发生的是您正在访问 window.name

What is happening here is that you are accessing window.name.

这是一个窗口上的预定义属性,因此您提升的 var name 实际上并未创建新变量。全局范围内已有一个具有该名称,并且默认情况下,它具有空字符串值。

This is a predefined property on window, so your hoisted var name isn't actually creating a new variable. There's already one in the global scope with that name and by default, it has a blank string value.

要观察您期望的行为,可以使用变量名称除 name 之外,或将您的代码放在函数中:

To observe the behavior you were expecting, you can use a variable name other than name, or put your code inside a function:

function hoisting() {
  console.log("A: My name is " + name);   

  function happy() {
    console.log ("1: I am " + feeling);   
    var feeling = "happy";
    console.log ("2: I am " + feeling);   
  }
  happy(); 

  var name = "Jim";
  console.log("B: My name is " + name);   
}

hoisting();

这篇关于为什么我的JavaScript提升局部变量返回undefined但是提升的全局变量返回空白?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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