JS稀奇古怪题目
JS稀奇古怪题目:
1.操作对象属性优先级高于普通赋值操作
1 var a = { 2 n: 1 3 }; 4 var b = a; 5 6 //操作对象属性优先级高于普通赋值操作 7 a.x = a = { 8 n: 2 9 }; 10 11 console.log(a.n, b.n); // 2 1 12 console.log(a.x, b.x); //undefined Object
2.作用域只有局部和全局,没有对象作用域。
只能查找局部和全局作用域
1 var obj = { 2 fn2:function(){ 3 console.log(fn2); 4 } 5 } 6 obj.fn2(); //error: fn2 is not defined
修改绑定当前调用对象obj
1 var obj = { 2 fn2:function(){ 3 console.log(this.fn2); 4 } 5 } 6 obj.fn2(); //function(){console.log(this.fn2);}
3.变量提升
1 var a = 2; 2 function fn(){ 3 //局部变量提升 4 console.log(a); 5 var a = 3; 6 7 } 8 fn(); //undefined 9 10 11 function fn2(){ 12 console.log(a); 13 a = 3; 14 15 } 16 fn2(); //2 [局部没有a,全局此时为2,之后为3]
只看全局和function作用域不看if则if中的var name 变量提升了:
1 var name = "hello"; 2 3 (function(){ 4 if(typeof name === 'undefined'){ 5 var name = 'world'; 6 console.log(name); 7 }else{ 8 console.log(name); 9 } 10 })(); //word
4.同名变量和函数
首先变量提升,但函数声明总是覆盖同名变量
- 如果同名变量没有赋值,则类型一定是function 如果同名变量赋值了,
- 如果打印语句在赋值之后,则类型一定是number
- 如果打印语句在赋值之前,则类型一定是function
(1)变量在函数前且有赋值
1 var b; 2 function b(){ 3 4 } 5 console.log(typeof b); //function 6 7 console.log(typeof b); //function
(2)变量在函数前且无赋值
1 var b = 3; 2 function b(){ 3 4 } 5 console.log(typeof b); //number 6 7 console.log(typeof b); //number
(3)变量在函数后且无赋值
1 function b(){ 2 3 } 4 var b; 5 console.log(typeof b); //function 6 7 console.log(typeof b); //function
(4)变量在函数后且有赋值
1 function b(){ 2 3 } 4 var b = 3; 5 console.log(typeof b); //number 6 7 console.log(typeof b); //number
5.线程
主线程执行完毕之后,在从callback queue中取回调函数执行
var a = 6; setTimeout(function(){ console.log(0); alert(a); a = 666; },0); console.log(1); a = 66;
执行主线程: 打印1,然后a = 66,在执行定时器回调函数打印0,弹框值66
6.原型链
注意:是在Function的原型上加方法,不是在F函数对象上加方法
1 // var F = function(){} 2 3 function F(){ 4 5 } 6 7 Object.prototype.a = function(){ 8 console.log("a()"); 9 } 10 11 Function.prototype.b = function(){ 12 console.log("b()"); 13 } 14 15 var f = new F(); 16 17 F.a();//a() 18 F.b();//b() 19 f.a();//a() 20 f.b();//报错