关于this对象,首先明确this对象是在运行时基于函数的执行环境而决定的,在全局函数中,this就等于window,而当函数被作为某个对象的方法被调用时,this就等于那个对象;
遵循两个原则:在函数中直接使用;函数作为对象的方法被调用(谁调用我,我就指向谁);阿里的关于this的面试题如下:
var name=222;
var obj={
name:111,
say:function(){
console.log(this.name);
}
}
var fun=obj.say;
fun();//222 相当于fun.call(window) 只给say方法时代表的就是window对象,this指向window
obj.say();//111 this指向obj
var b={
name:333,
say:function(fun){
fun();
}
}
b.say(obj.say);//222 obj的say的this指向window
b.say=obj.say;
b.say();//333 将obj的方法直接赋值给b,this指向b
es6的箭头函数中的this判别:箭头函数中的this在定义函数的时候绑定,而不是执行函数的时候绑定;this指向的固定化,实际上箭头函数没有自己的this,导致内部的this就是外层代码块(父级)的this;
var x=11;
var obj={
x:22,
say:()=>{
console.log(this.x);
}
}
// 定义的时候绑定this,就是this继承自父级执行上下文中的this
// 箭头函数say与obj是平级,obj的父级是window
obj.say();//11
var obj2={
birth:1990,
getAge:function(){
var b=this.birth;//1990
// 此处的箭头函数的this会找到父级getAge的,也就是obj2
var fn= ()=>{
console.log(this.birth);
};
return fn();
}
}
obj2.getAge(); //1990