🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[TOC] eg1 变量提升 ``` console.log(a); //undefined var a = 12; function fn(){ console.log(a); var a = 13; } fn(); //undefined console.log(a); //12 ``` eg2 作用域链的超找 ``` console.log(a); //undefined var a = 12; function fn(){ console.log(a); a = 13; } fn(); //12 console.log(a); //13 ``` eg3 作用域链的超找 ``` console.log(a); //报错 a = 12; function fn(){ console.log(a); a = 13; } fn(); console.log(a); ``` eg4 判断体与提升 不管条件成立不成立都会提升, 但新版浏览器中只有条件成立,进入判断体后才会成立 ``` var foo = 1; function bar(){ if(!foo){ var foo = 10; } console.log(foo); } bar(); //10 ``` --- eg5 提升与函数执行过程 ``` var foo = 'hello'; (function(foo){ //=>私有作用域:foo='hello'(我们的foo和外面的foo是不同的变量) console.log(foo); //hello var foo = foo || 'world'; console.log(foo);//hello })(foo); //=>把全局FOO的值当做实参传递给私有作用域中的形参 console.log(foo);//hello ``` eg6 作用域链,与函数执行 var a = 9; function fn(){ a = 0; return function (b){ return b+a++; } } var f = fn(); console.log(f(5)); //会将a置为0//5 cosnole.log(fn()(5)); //会将a置为0//5 console.log(f(5)); //不会再将a置为0,此时a=1 //6 console.log(a); //2 ``` eg7 私有变量和全局变量没有直接的关系,但是可能存在间接的关系 =>私有变量和全局变量都是引用数据类型的值,而且指向的是相同的堆内存 ``` var ary = [1,2,3,4]; function fn(ary){ ary[0] = 0; //这里改变的第一个数组成员 ary = [0]; //这里指向了另一个地址 ary[0] = 100; //将新地址中的第一个成员设置为了100 return ary; //返回新地址 } var res = fn(ary); console.log(ary); //[0,2,3,4] console.log(res); //[100] ``` ![](https://box.kancloud.cn/8207d77dfa1a8b0000b38ba3b7bc65b3_1811x707.png) eg8 ``` function fn(i){ return function(n){ console.log(n + (--i)); } } var f = fn(2); f(3); //4 fn(4)(5); //8 fn(6)(7); //12 f(8); //8 ``` eg9 ``` var num = 10; var obj = {num:20}; obj.fn = (function(num){ //私有20 this.num = num*3; //全局num = 60; num++; //私有21; return function(n){ this.num += n; //全局65 //obj.num->30 num++; //私有22 //私有23 console.log(num); } })(obj.num); var fn = obj.fn; fn(5); //22 obj.fn(10); //23 console.log(num,obj.num); //65 30 ```