function ppp(){
var a = 2;
sss = function(){
console.log(a);
}
}
ppp();
sss()//这里能打印2感觉很神奇,因为2在ppp函数作用域里面,sss在外面执行竟然能拿到值
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
你的理解完全错了, 首先 你这样 直接写 a =2; 实际相当于 声明了个全局变量 ,你可以理解为 window.a =2;当然能拿到。
你是 JS 新手?这里 sss 和 a 都已经是全局变量了,当然sss在外面执行也能拿到值。建议补充一下 JS 的作用域和闭包相关知识。
你没用var 关键字 你的a 实际上是全局变量啊。
简单的回答下吧:
你使用严格模式试试,
"use strict"这段代码是会报错的你ppp函数里面,变量
a和变量sss都没有用var声明,所以在非严格模式中,它自动绑定到了window中,也就是相当于window.a=×××,window.sss=×××,所以自然你在外面执行sss能正常运行,同时也能打印其实这倒题目里面也有一个闭包,改严谨一点:
改成这样的话,a是一个函数内的局部变量,然后这就形成了一个闭包,在外部掉sss就能得到或输出a(这就是类似于Class中的Get和Set了)
另外,建议平时还是使用
"use strict"这个好习惯,毕竟ES6就都是秧歌模式了。推荐下
YDKJS,摘自里面的一段话。Let's consider this block of code:
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,barandb.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
baris entirely contained within the bubble forfoo, because (and only because) that's where we chose to define the functionbar.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(){
};
这个是一个全局函数,但是它存在于pop函数的执行环境内所以能访问到变量a