有这样的 JavaScript 代码:
执行后它会打印出:3,类型错误。请问有人能解释一下为什么吗?
function a() {
a = 3;
return a;
}
console.log(a());
console.log(a());
执行后它会打印出:3,类型错误。请问有人能解释一下为什么吗?
function a() {
a = 3;
return a;
}
console.log(a());
console.log(a());
你有作用域问题
因为你没有使用"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
你想要什么
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
在函数中几乎总是推荐使用var,否则就会污染或更糟地覆盖全局变量。
在JS中,使用var
可以将变量强制转换为局部作用域(函数内)。
请注意,在全局范围内使用var
仍然会创建一个全局变量。
a
设置为变量,则需要在前面加上 var
。因为您没有这样做,它会暴露到全局作用域中,其中它是 window
对象的一部分,并且您可以使用 window.a
访问它。所以,最好的做法是将函数的第一行修改为: var a = 3
。