例1:
function fn(a){
console.log(a);//function (){}
var a = 123;
console.log(a);//123
function a(){}//预编译看过的地方不再看
console.log(a);//123
var b = function(){}
console.log(b);//function(){}
function c(){}//function c(){}
}
fn(1);
//预编译发生在函数执行的前一刻
1. 创建AO对象(Activition Object)(执行期上下文)
AO{}
2. 找形参和变量声明,将变量和形参名名作为AO对象的属性名,值是undefined
AO{
a:undefined,
b:undefined,
}
3. 将实参和形参统一
AO{
a:1,
b:undefined,
}
4. 在函数体里面找函数声明,值富裕函数体
AO{
a:function (){},
b:undefined,
c:function c(){}
}
5. 执行语句(解释执行(解释一行、执行一行))
AO{
a:123,
b:function(){},
c:function c(){}
}
例2:
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);
1. 创建AO对象(Activition Object)(执行期上下文)
AO{}
2. 找形参和变量声明,将变量和形参名名作为AO对象的属性名,值是undefined
AO{
a:undefined,
b:undefined,
}
3. 将实参和形参统一
AO{
a:1,
b:undefined,
}
4. 在函数体里面找函数声明,值赋予函数体
AO{
a:function a(){},
b:undefined,
}
5. 执行语句(解释执行(解释一行、执行一行))
AO{
a:function a(){} 》123
b:undefined 》234 》function(){}
}
例3:
console.log(test);//function test(test){...}!function test(test){...}!function test(test){...}!重要事情说3遍
function test(test){
console.log(test);//function test(){}
var test = 234;
console.log(test);//234
function test(){}
}
test(1);
var test = 123;
例4:
global = 100;
function fn(){
console.log(global);//undefined!undefined!undefined重要事情说3遍,有自己的用自己的global,不用全局的
global = 200;
console.log(global);//200
var global = 300;
}
fn();
var global;
例5:
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(a);//234
例6:
function bar(){
return foo;
foo = 10;
function foo(){
body...
}
var foo = 11;
}
document.write(bar());
//function foo(){
// body...
// }
例7:
document.write(bar());
function bar(){
foo = 10;
function foo(){
//body...
}
var foo = 11;
return foo;
}
//11
例7:
a = 100;
function demo(e){
function e(){}
arguments[0] = 2;
document.write(e);//2
if(a){
var b = 123;
function c(){}
}
var c;
a = 10;
var a;
document.write(b);//undefined
f = 123;
document.write(c);
//不是function c(){}而是undefined(规则改变了:function不能出现在if语句里)
//不是function c(){}而是undefined(规则改变了:function不能出现在if语句里)
//不是function c(){}而是undefined(规则改变了:function不能出现在if语句里)
document.write(a);//10
}
var a;
demo(1);
document.write(a);//100
document.write(f);//123
例8:
var str = false + 1;
document.write(str);//1
var demo = false == 1;
document.write(demo);//0错误!应该是false!false!false!
// undefined -1 NaN 空字符串
if(typeof(a) && -true + (+undefined) + ""){
// "undefined" && "NaN" 真真为真
document.write('基础扎实');
}
if(11 + '11' * 2 == 3){
document.write('基础扎实');
}
// false!
// false!
// false!
!!" " + !!"" - !!false || document.write('不能打印');
//true + false - flase = true
例9:
(window.foo || (window.foo = 'bar'));
document.write(window.foo)
//①先执行window.foo = 'bar',
//②执行window.foo为true
//③打印