Javascript从零基础到精通——函数(下)
匿名函数
没有名字的函数
function () {
console.log(123)
}
var test = function () {
console.log(123)
}
div.onclick = function () {
console.log(123)
}
自调用函数(IIFE)
Immediately Invoked Function Expression ( 立即调用函数表达式)
;(function () {
console.log(123)
})()
注意:自调用函数如果前一行没有分号,要在前面加上分号
JS运行和编译
- 语法分析
查找基本语法有没有错误 - 预解析
执行之前进行预解析
var、function关键字提前到当前作用域的顶部,变量默认值为undefined,函数默认值为函数体代码块,当函数与变量重名时,保留函数。 - 解释执行
预编译
请回答下面这道题:
alert(a); // function a(){alert(3);}
var a = 1;
alert(a); // 1
function a(){alert(2);}
alert(a); // 1
var a = 3;
alert(a); // 3
function a(){alert(3);}
alert(a); // 3
预编译中有两种提升:
- 变量提升:把var声明的变量提升到当前作用域的顶部,只提升声明,不提升赋值
- 函数声明整体提升
预编译四部曲:
- 创建AO对象 Activation Object (执行期上下文)
- 找形参和变量声明,将变量和形参名作为AO属性名,值为undefined
- 将实参值和形参统一
- 在函数体里面找函数声明,值赋予函数体
预编译练习题
function test(a, b) {
console.log(a); // 1
c = 0;
var c;
a = 3;
b = 2;
console.log(b); // 2
function b() { }
function d() { }
console.log(b); // 2
}
test(1);
function test(a, b) {
console.log(a); // function a() { }
console.log(b); // undefined
var b = 234;
console.log(b); // 234
a = 123;
console.log(a); // 123
function a() { }
var a;
b = 234;
var b = function () { }
console.log(a); // 123
console.log(b); // function () { }
}
test(1);
function test() {
var a = b = 123;
console.log(window.a); // undefined
console.log(window.b); // 123
}
test();
console.log(test); // function() {}
function test(test) {
console.log(test); // function() {}
var test = 234;
console.log(test); // 234
function test() { }
}
var global = 100;
function fn() {
console.log(global); // 100
}
global = 100;
function fn() {
console.log(global); // undefined
global = 200;
console.log(global); // 200
var global = 300;
}
fn();
var global;
function test() {
console.log(b); // undefined
if (a) {
var b = 100;
}
console.log(b); // undefined
c = 234;
console.log(c); // 234
}
var a;
test();
a = 10;
console.log(c); // 234
function bar() {
return foo;
foo = 10;
function foo() {
// body...
}
var foo = 11;
}
console.log(bar()); // function() {}
console.log(bar()); // 11
function bar() {
foo = 10;
function foo() {
// body...
}
var foo = 11;
return foo;
}
console.log(b); // undefined
var b = function() {}
a = 100;
function demo(e) {
function e() {}
arguments[0] = 2;
console.log(e); // 2
if(a) {
var b = 123;
function c() {
}
}
var c;
a = 10;
var a;
console.log(b); // undefined
f = 123;
console.log(c); // function() {}
console.log(a); // 10
}
var a;
demo(1);
console.log(a); // 100
console.log(f); // 123

浙公网安备 33010602011771号