Var的变量,函数没有Var

时间:2018-06-01 14:14:35

标签: javascript scope

局部变量oopsGlobal,在函数fun1之外使用时会出错,但以相同方式定义的另一个变量name不会产生错误,并且可以在函数外部访问?

我在这里错过了什么吗?



function functionName() {
  // variables created without Var always global scope
  var name = "sudeep";
  console.log("myfirst function");
}

function functionName1() {
  // variables created without Var always global scope
  console.log("Local variable with var:" + name);
}
// Declare your variable here
var myGlobal = 10;

function fun1() {
  // Assign 5 to oopsGlobal Here
  var oopsGlobal = 5; //local scope to variable when accessed outside gives error so working fine
}

functionName();
functionName1();
console.log(name); // **does not give error at all**
fun1();
console.log(name); //**does not give error at all**
console.log(oopsGlobal); //give error so works fine




enter image description here

0 个答案:

没有答案