JavaScript this 指针
this:指向调用它的对象。根据以下几种使用场景进行详细介绍。
构造函数:
function Bai(age){
this = {};//this先指向一个空对象
this.age= age;//对this赋值
return this;//返回this
}
var B = new Bai('18岁');
对象属性:
var student ={
age:'18',
printAge:function(){
console.log(this.age)
}
};
student .printName();//18这个时候this指向student对象,this === student;
普通函数:
function Bai(){
console.log(this);//this指向window;
}
利用call或者apply改变this指向:
当使用apply和call上下文调用的时候this指向传入的第一个参数
var obj = {}
function func(){
console.log(this)
}
func() // this -> window
func.call(obj) // this -> obj
func.apply(obj) // this -> obj