JavaScript 里的变量和函数提升

变量提升

示例1:

console.log(varName) // output: undefined

var varName = 'i am varName'

console.log(varName) // output: i am varName

由于变量提升,上面等同于

var varName
console.log(varName)
varName = 'i am varName'
console.log(varName)

示例2:

var name = 'Lilei'

(function () {

  console.log(name) // output: undefined

  var name = 'Hanmeimei'

  console.log(name) // output: Hanmeimei

})()

函数提升

示例:

foo() // output: i am foo
varName() // output: Uncaught TypeError: varName is not a function
funcName() // output: Uncaught ReferenceError: funcName is not defined (for ie8, output: i am funcName

function foo() { // function declarations
  console.log('i am foo')
}

var varName = function funcName() { // function expression
  console.log('i am funcName')
}

函数定义会提升,函数表达式不会(但IE8也会提升)

函数表达式(function expression) 是指

var myFunction = function [name]([param1[, param2[, ..., paramN]]]) {
   statements
};

参考资料

http://adripofjavascript.com/blog/drips/variable-and-function-hoisting

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function

huang.xinghui

Programmer

huang-x-h huangxinghui


Published