我正在学习javascript提升功能,并发现以下代码非常令人困惑:
var a = 1;
function b() {
a = 10;
return;
function a() {}
}
b();
alert(a);输出为1。据我所知,由于hoisting,上面的代码相当于
var a;
function b() {
function a() {}
a=10;
return;
}
a=1;
b();
alert(a);当function和variable同名为a时会发生什么?
发布于 2015-12-06 01:10:09
当一个函数和一个变量同名为a时,会发生什么情况?
没有什么特别事情。a的一个赋值覆盖另一个赋值,因为它们都是值。
console.log(a) // a points to a function here
var a = 4
console.log(a) // a points to 4 here
function a() {}
console.log(a) // a also points to 4 here!顺便说一句,只有当变量不是函数的本地变量时,函数以外的作用域中的变量才能被该函数修改。
var a = 4
;(function() {
a = 5
})() // <-- Immediately calling the function here
console.log(a) // a is now 5
;(function() {
a = 6
var a
})()
// a is still 5 because in the previous function,
// a was local to the function's scope
console.log(a)函数参数隐式地定位于变量,因此它们自动“阴影”共享相同的名称。
发布于 2015-12-06 01:02:49
在b中,首先将局部变量a设置为函数,然后设置值10。外部变量a不受影响,因为它是由局部变量a在b中隐藏的。也许这个大致相同的代码将有助于说明:
var a = 1;
function b() {
var a;
a = function a() { };
a = 10;
return;
}
b(); // Basically a no-op
alert(a);发布于 2015-12-06 01:07:45
职能:
function b() {
a = 10;
return;
function a() {}
}基本上与此相同,因为hoisting将函数推到其作用域的顶部:
function b() {
function a() {}
a = 10;
return;
}同样重要的是要注意,function a() {}与编写var a = function() {}是一样的。所以现在,我们有这样的东西:
function b() {
var a = function() {}
a = 10;
return;
}由于在函数b()中声明了一个名为a的变量,因此b()只在其本地作用域中使用和更改该a,因此在函数b()之外声明的a未被更改。
https://stackoverflow.com/questions/34112768
复制相似问题