以下内容针对ES5
一,先说下变量提升:
1,全局执行上下文中(一段script):变量定义,函数声明(执行之前)
console.log(a) //undefined var a = 20;
以上代码等同于:
var a; //变量提升到全局执行上下文顶部,默认值为undefined console.log(a); //undefined a = 20;
再看函数声明:
fn('zs') //zs 20 function fn(name) { age = 20; console.log(name, age); var age; }
以上代码等同于:
function fn(name) { //函数声明整体提升到全局执行上下文的顶部 var age;//变量提升到函数执行上下文顶部 age = 20; console.log(name, age); } fn('zs') //zs 20
备注:还是要规范编写函数。不推荐上述写法,要先定义后执行,增加可读性。
另外,注意函数声明和函数表达式的区别,函数声明可以在定义之前执行,函数表达式不可以,会报错。Uncaught TypeError: fn1 is not a function
2,函数执行上下文中:变量定义,函数声明,this,arguments(执行之前)
二,JS作用域:
1,没有块级作用域
// 没有块级作用域 if(true) { var name = 'lily' } console.log(name); //lily
以上代码等同于如下代码(推荐如下写法):
var name; if(true) { name = 'lily'; } console.log(name); //lily
2,只有函数和全局作用域
作用域链:在试图访问一个变量时,JS引擎会从当前作用域开始向上查找直到Global全局作用域停止,作用域组成的有序集合就成为作用域链。

函数的作用域和父级作用域,是定义时候的作用域,不是执行时候的


三,关于this
this是Javascript语言的一个关键字。this对象是在运行时基于函数的执行环境绑定的(this要在执行时才能确认值,定义时无法确认)

this几种不同使用场景
1,作为构造函数执行
2,作为普通函数执行
3,作为对象属性执行
4,call,apply,bind


四,闭包
闭包就是能够读取其他函数内部变量的函数。
闭包的使用场景:函数作为返回值,函数作为值传递

实际开发中闭包的作用

最后,来个小例子:创建10个a标签,点击的时候弹出来对应的序号
