Js作用域练习demo1
var v = "hello";
(function(){
alert(v);
var v = "world";
})();
alert(v);
//以上代码执行如下
var v = "hello";
(function(){
VO = {
arguments:{ },
v:undefined
}
alert(v);//undefined
v = "world";
})();
alert(v);//hello
Js作用域练习demo2
(function(){
alert(a+b+c);//NaN
var a = "1";
var f = function(){};
var b = "2";
var c = "3";
})();
//以上代码执行如下
(function(){
VO = {
arguments:{},
a:undefined,
f:undefined,
b:undefined,
c:undefined
}
alert(a+b+c);//NaN
a = "1";
f = function(){};
b = "2";
c = "3";
})();
JS作用域练习demo3
//函数声明是整体提升
//函数表达式 只提升声明的变量 不会带着函数体一起提升
(function(){
f2(); //2
f1(); //报错f1 is not a function
var f1 = function(){
alert(2)
};
function f2(){
alert(1);
}
})();
//以上代码执行如下
(function(){
VO = {
arguments:{},
f2:function () {
alert(1);
},
f1:undefined,
}
f2(); //1
f1(); //报错f1 is not a function
f1 = function(){
alert(2)
};
})();
JS作用域练习demo4
var a = 1;
function outer(){
var b = 2;
function inner(){
var c = 4;
alert(a);//1
}
inner();
}
outer();
JS作用域练习demo5
var a = 1;
function check(){
a = 100;
alert(a);//100
}
check();
alert(a);//100
JS作用域练习demo6
var v = "hello";
if(true){
alert(v); //hello
var v = "world";
}
alert(v); //world
//以上代码执行如下
VO = {
v:undefined,
}
v = "hello";
if(true){
alert(v);//hello
v = "world";
}
alert(v);//world
JS作用域练习demo7
function rain(){
var x = 1;
function man(){
x = 100;
}
man();
alert( x );
}
rain();
//以上代码执行如下
function rain(){
VO = {
arguments:{},
x:undefined,
}
x = 1;
function man(){
VO = {
arguments:{}
}
x = 100;
}
man();
alert( x );//100
}
rain();
JS作用域练习demo8
var x = 1;
function rain(){
alert( x );//undefined
var x = 'man';
alert( x );//man
}
rain();
//以上代码执行如下
var x = 1;
function rain(){
VO = {
arguments:{},
x:undefined
}
alert( x );//undefined
x = 'man';
alert( x );//man
}
rain();
JS作用域练习demo9
function rain(){
x = 100;
}
rain();
alert( x );//100
JS作用域练习demo10
var t='a';
function test2(){
alert(t);//undefined
var t = 'b';
alert(t);//b
}
test2();
JS作用域练习demo11
var t='a';
function test2(){
alert(t);//a
t = 'b';
alert(t);//b
}
alert(t);//a
test2();
alert(t);//b
JS作用域练习demo12
var a="Hello";
function test(){
alert(a); //Hello
a="World";
alert(a); //World
}
test();
JS作用域练习demo13
var a =1;
function test(){
alert(a);//udefined
a=4;
alert(a)//4
var a=2;
alert(a);//2
}
test();
alert(a);//1
最后
这些题目在大多数面试中可能都会遇到,知其原理才能看清每个题目的套路在哪里。
网友评论