var a=new function(){}与function a(){}的区别


 若是咱们使用 匿名函数express

var FUNCTION_NAME = function() { /* FUNCTION_BODY */};


这种方式, 编译后变量声明FUNCTION_NAME 会“被提早”了,可是他的赋值(也就是FUNCTION_BODY)并不会被提早。
也就是说,匿名函数只有在被调用时才被初始化。

若是咱们使用函数

function FUNCTION_NAME () 
{ /* FUNCTION_BODY */};


这种方式, 编译后函数声明和他的赋值都会被提早。
也就是说函数声明过程在整个程序执行以前的预处理就完成了,因此只要处于同一个做用域,就能够访问到,即便在定义以前调用它也能够。

 code

function hereOrThere() { //function statement
  return 'here';
}

alert(hereOrThere()); // alerts 'there'

function hereOrThere() {
  return 'there';
}

咱们会发现alert(hereOrThere) 语句执行时会alert('there')!这里的行为其实很是出乎意料,主要缘由是JavaScript 函数声明的“提早”行为,简而言之,就是Javascript容许咱们在变量和函数被声明以前使用它们,而第二个定义覆盖了第一种定义。换句话说,上述代码编译以后至关于ip

function hereOrThere() { //function statement
  return 'here';
}

function hereOrThere() {//申明前置了,但由于这里的申明和赋值在一块儿,因此一块儿前置
  return 'there';
}

alert(hereOrThere()); // alerts 'there'

再看下面一个例子:作用域

 

var hereOrThere = function() { // function expression
  return 'here';
};

alert(hereOrThere()); // alerts 'here'

hereOrThere = function() {
  return 'there';
};

这里就是咱们期待的behavior,这段程序编译以后至关于:
 io

var hereOrThere;//申明前置了

hereOrThere = function() { // function expression
  return 'here';
};

alert(hereOrThere()); // alerts 'here'

hereOrThere = function() {
  return 'there';
};
相关文章
相关标签/搜索