Why is my JavaScript hoisted local variable returning undefined but the hoisted global variable is returning blank? [duplicate]

梦想的初衷 提交于 2019-12-17 14:44:28

问题


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);   

I expected the following results:

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

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.

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


回答1:


What is happening here is that you are accessing window.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.

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();


来源:https://stackoverflow.com/questions/27713457/why-is-my-javascript-hoisted-local-variable-returning-undefined-but-the-hoisted

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!