OLe*_*ACH 5 javascript function console.log
有这样的JavaScript代码:
function a() {
a = 3;
return a;
}
console.log(a());
console.log(a());
Run Code Online (Sandbox Code Playgroud)
执行后打印出:3,输入错误.请有人解释原因
Seb*_*iel 11
你有一个范围问题
因为您没有使用"var",所以使用数字(3)覆盖全局"a"变量(以前是您的函数).
当你第二次尝试执行它时,它不再是一个函数而是一个数字,它会抛出类型错误.
function a() {
a = 3; // you just over-wrote a()
return a;
}
console.log(a()); // 3, but now "a" === number, not function
console.log(a()); // ERROR, you treated "a" as a function, but it's a number
Run Code Online (Sandbox Code Playgroud)
你想要什么
function a() {
var a = 3; // using var makes "a" local, and does not override your global a()
return a;
}
console.log(a()); // 3
console.log(a()); // 3
Run Code Online (Sandbox Code Playgroud)
建议几乎总是在函数内部使用var,否则您将污染或更糟糕地覆盖全局变量.在JS中,var将您的变量强制执行到本地范围(您的函数).
请注意,在全局范围中使用var仍会创建全局变量