你不知道的javaScript笔记(1)

规避冲突

function foo(){

function bar(a){

i = 3;

console.log(a + i);

}

for ( var i=0; i < 10; i++){

bar(i * 2)

}

}

  // 11无限死循环

 

区分函数声明和函数表达式最简单的方法是看 function 关键字出现的位置,如果function是声明中的第一个词,那么是函数声明,否则是函数表达式。

(function foo(){})() 立即执行的函数表达式

 

IIFE 立即执行函数表达式

var a = 2; 

(function IIFE(global){

var a = 3;

console.log(a); // 3

console.log(global.a) // 2

})(window)

console.log( a)  // 2

 

将window 对象的引用传递进去,当然可以从外部作用域传入进任何你需要的东西,

并可以将变量命名为任何你觉得合适名字。

var a = 2;

(function IIFE(def) {

    def(window)

})(function def(global) {

    var a = 3;

    console.log(a); // 3

    console.log(global.a) //2

});

         函数表达式def 定义在片段的第二部分,然后当做参数被传递进IIFE 函数定义的第一部分中。最后def也就是传递进去的函数被调用,并将window 传入当做global参数的值。

 

try/catch 的catch 分句会创建一个块级 作用域,其中声明的变量仅在catch内部有效

例如:try{

undefinde();

}catch (err){

console,log(err); // 能够正常使用

  }

  console.log(err)  // ReferenceError: err not found

let 块作用域

var foo = true;

if(foo){

let bar = foo *2;

bar  = something(bar);

console.log(bar);

}

console.log(bar); // ReferenceError

 

变量提升,先有声明后又赋值。

foo();

function foo(){

console.log(a); // undefinded

var a = 2;

}

 原因:相当于以下

  function foo(){

var  a;

console.log(a); // undefined

a = 2;

}

foo();

 

注意: 函数声明会被提升,函数表达式不会被声明。函数和变量都会被提升,但是函数会被提前提升,然后是变量。

foo();   //1

var foo;

function foo(){

console.log(1);

}

foo = function() {

console.log(2)

}

  const  常量

 

后面的函数声明会覆盖前面的

foo(); // 3

function foo(){

console.log(1);

}

var foo = function() {

console.log(2);

}

function foo(){

console.log(3);

}

var a = 2 ; 的解析原则是  var  a 和  a = 2  当做两个单独的声明,第一个是编译阶段的

任务,第二个是执行阶段的任务。

 

闭包

function foo() {

var a = 2;

function bar(){

console.log(a);

}

return bar;

}

var baz = foo();

baz(); // 2

var fn;

function foo() {

var a  = 2;

function baz() {

console.log(a)

}

bar(baz);

}

function bar(fn){

fn();

}

for(var i = 1; i<=5; i++){

(function(j){

setTimeout(function(){

console.log(j)

},j*1000)

})(i)

}

在迭代器内部使用IIFE会为每一个迭代都生成一个新的作用域。

 

块作用域和闭包联手

for(var i = 1; i <= 5; i++){

setTimeout(function timer(){

console.log(i)

},i*1000)

}

模块

function  CoolModule(){

var  something = "cool";

var another = [1,2,3];

function doSomething() {

console.log(something);

}

function doAnoth(){

console.log(another.join("!"));

}

return {

doSomething: doSomething,

doAnother: doAnother

};

}

var  foo = CoolModule();

foo.doSomething(); //cool

foo.doAnother() // 1!2!3

 

改为单例模式:

var foo = (function CoolModule(){

var something = "cool";

var another = [1,2,3];

function doSomething() {

console.log(something)

}

 

function doAnother(){

console.log(another.join("!"))

}

 

return {

doSomething: doSomething,

doAnother: doAnother

}

})();

foo.doSomething(); // cool

foo.doAnother(); //1!2!3

 

posted @ 2017-06-27 15:40  柠檬先生  阅读(190)  评论(0编辑  收藏  举报