function ppp(){
var a = 2;
sss = function(){
console.log(a);
}
}
ppp();
sss()//这里能打印2感觉很神奇,因为2在ppp函数作用域里面,sss在外面执行竟然能拿到值
function ppp(){
var a = 2;
sss = function(){
console.log(a);
}
}
ppp();
sss()//这里能打印2感觉很神奇,因为2在ppp函数作用域里面,sss在外面执行竟然能拿到值
简单的回答下吧:
你使用严格模式试试,"use strict"
这段代码是会报错的
你ppp函数里面,变量a
和变量sss
都没有用var声明,所以在非严格模式中,它自动绑定到了window中,也就是相当于window.a=×××,window.sss=×××
,所以自然你在外面执行sss能正常运行,同时也能打印
其实这倒题目里面也有一个闭包,改严谨一点:
function ppp(){
var a = 2;
return sss = function(){
console.log(a);
return a;
}
}
console.log(ppp()()); //2,2
改成这样的话,a是一个函数内的局部变量,然后这就形成了一个闭包,在外部掉sss就能得到或输出a(这就是类似于Class中的Get和Set了)
另外,建议平时还是使用"use strict"
这个好习惯,毕竟ES6就都是秧歌模式了。
推荐下YDKJS
,摘自里面的一段话。
Let's consider this block of code:
function foo(a) {
var b = a * 2;
function bar(c) {
console.log( a, b, c );
}
bar(b * 3);
}
foo( 2 ); // 2 4 12
There are three nested scopes inherent in this code example. It may be helpful to think about these scopes as bubbles inside of each other.
Bubble 1 encompasses the global scope, and has just one identifier in it: foo
.
Bubble 2 encompasses the scope of foo
, which includes the three identifiers: a
, bar
and b
.
Bubble 3 encompasses the scope of bar
, and it includes just one identifier: c
.
Scope bubbles are defined by where the blocks of scope are written, which one is nested inside the other, etc. In the next chapter, we'll discuss different units of scope, but for now, let's just assume that each function creates a new bubble of scope.
The bubble for bar
is entirely contained within the bubble for foo
, because (and only because) that's where we chose to define the function bar
.
Notice that these nested bubbles are strictly nested. We're not talking about Venn diagrams where the bubbles can cross boundaries. In other words, no bubble for some function can simultaneously exist (partially) inside two other outer scope bubbles, just as no function can partially be inside each of two parent functions.
var a = 2;
这个不是全局变量,而是pop方法的一个局部变量而已,
sss = function(){
console.log(a);
};
这个是一个全局函数,但是它存在于pop函数的执行环境内所以能访问到变量a
10 回答11.2k 阅读
5 回答4.8k 阅读✓ 已解决
4 回答3.1k 阅读✓ 已解决
2 回答2.8k 阅读✓ 已解决
3 回答2.3k 阅读✓ 已解决
3 回答2.2k 阅读✓ 已解决
2 回答2.6k 阅读✓ 已解决
你的理解完全错了, 首先 你这样 直接写 a =2; 实际相当于 声明了个全局变量 ,你可以理解为 window.a =2;当然能拿到。