javascript - 函数中带 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
解决方案
推荐阅读
- javascript - UnhandledPromiseRejectionWarning:错误:无效整数:
- intellij-idea - 如何映射一个
在 PhpStorm 中使用 IdeaVim? - typescript - 从泛型类中获取方法的参数 - TypeScript
- c - 源文件更改时二进制文件不重建
- react-native - 如何在保持位置的同时放大图像?
- jquery - jQuery 预加载大图像,加载进度更新百分比
- redis - 我可以在一个微服务域中使用 redis master 并由不同的微服务使用 redis slave 作为共享数据的一种方式吗?
- r - R:更新 XML 文件中的数据
- python - 正则表达式:匹配字符串后跟点/逗号后跟空格
- python - 通过 boto3 更新 Glue 作业返回 InvalidInputException 错误