🍕 面试题基础版
// 🍕 面试题1
var a=1;
function test(){
var a=2;
function bar(){
var a=3;
console.log(this.a); //global Undefined
}
bar();
}
test(); //Undefined 应该是1吧
// 疑问❓:浏览器运行是1,node运行时undefined
// ∵this的取值跟调用方式有关,bar()的调用方式,函数名前没'.',指向全局变量。
// 🍕 面试题2
let obj={
length:1,
foo:function(){
console.log(this.length);
}
}
[1,2,3,obj.foo,5][3](); //5
//----解题过程
var arr=[1,2,3,obj.foo,5];
arr[3]();
// obj.foo本质是一个指针,指向一个匿名函数
var arr=[1,2,3,function(){console.log(this.length);},5];
arr.3();
// this-->arr arr.length=5
// 🍕 面试题3
var seller={
count:2;
getCount:function(){
return this.count;
}
};
var func=seller.getCount();
console.log(seller.getCount()); //2
console.log(func()); //Undefined 自调用
// 🍕 面试题4
var name='A';
var object={
name:'B';
getName:function(){
return function(){
return this.name
}
}
}
console.log(object.getName()()); //A
// var x=object.getName(); //x接收返回值,返回值是一个函数
// x(); //函数自调用 this-->window
//----------------------------------->修改缓存this
var name='A';
var object={
name:'B';
getName:function(){
var that=this;
return function(){
return that.name
}
}
}
console.log(object.getName()()); //B
🍕 面试题进阶版
// 🍕 面试题进阶版
var bar={name:'bar'};
var foo={
name:'foo',
say2:()=>{
console.log(this.name);
},
say3:function(){
return function(){
console.log(this.name);
}
},
say4:function(){
return()=>{
console.log(this.name)
}
}
};
foo.say2(); //Undefined 当前作用域没有去上层作用域(没有对象作用域)
foo.say2.call(bar); //Undefined 箭头函数不能强制指定this
foo.say3()(); //Undefined 返回一个函数,该函数自调用,this-->window
foo.say3().call(bar) //bar 强制绑定this-->bar
foo.say3.call(bar)() //Undefined 依旧是返回函数的自调用,改变上层函数this与它无关
foo.say4()() //foo 回一个函数,该函数自调用,but箭头函数this沿函数作用域链想上找
foo.say4().call(bar) //foo 箭头函数不能强制指定this
foo.say4.call(bar)() //bar 箭头函数this沿函数作用域链想上找,上层函数强制this-->bar