函数提升是把整个函数都提到前面去。函数表达式不能被提升,函数声明形式能被提升。
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<script>
//变量提升
function test(){
a=2;
var a;
console.log(a); //2
}
test();
//变量提升,不会把赋值也提升上来
var v='Hello World';
(function(){
var v;
console.log(v); //undefined
v='I love you';
})();
//函数声明形式能被提升
function myTest(){
foo();
function foo(){
console.log("hello world"); //hello world
}
}
myTest();
//函数表达式不能被提升
function myTest2(){
foo(); //foo is not a function
var foo =function foo(){
console.log("hello world");
}
}
myTest2();
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<script>
//输出Goodbye Jack
var name = 'World!';
(function () {
if (typeof name === 'undefined') {
var name = 'Jack';
console.log('Goodbye ' + name);
} else {
console.log('Hello ' + name);
}
})();
//输出Hello World!
var name2 = 'World!';
(function () {
if (typeof name2 === 'undefined') {
name2 = 'Jack';
console.log('Goodbye ' + name2);
} else {
console.log('Hello ' + name2);
}
})();
//输出Hello World!
var name3 = 'World!';
(function () {
if (typeof this.name3 === 'undefined') {
var name3 = 'Jack';
console.log('Goodbye ' + name3);
} else {
console.log('Hello ' + this.name3);
}
})();
</script>
</body>
</html