js的一个疑问?

function ppp(){
  var a = 2;
  sss = function(){
    console.log(a);
  }
}
ppp();
sss()//这里能打印2感觉很神奇,因为2在ppp函数作用域里面,sss在外面执行竟然能拿到值
阅读 3.3k
6 个回答

你的理解完全错了, 首先 你这样 直接写 a =2; 实际相当于 声明了个全局变量 ,你可以理解为 window.a =2;当然能拿到。

你是 JS 新手?这里 sss 和 a 都已经是全局变量了,当然sss在外面执行也能拿到值。建议补充一下 JS 的作用域和闭包相关知识。

你没用var 关键字 你的a 实际上是全局变量啊。

简单的回答下吧:

  1. 你使用严格模式试试,"use strict"这段代码是会报错的

  2. 你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

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题