首页 > 解决方案 > 函数中带 Var 和不带 Var 的变量

问题描述

局部变量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

在此处输入图像描述

标签: javascriptscope

解决方案


推荐阅读