this是 JavaScript 的一个关键字。在函数运行时,生成的一个内部对象,只能在函数内部使用,随着场景的不同,this也会发生变化。
总结一句话:this 就是指向调用函数的那个对象
四种场景:
1.单纯的函数调用
Code:
function one(){
this.x = 10;
console.info(this.x);
}
one();
console.info(x)
this代指window
2.作为对象方法调用
var stu = {
name:'admin',
age:20,
getStuInfos:function(){
//console.info(name+": "+age);
console.info(this.name+": "+this.age);
}
}
stu.getStuInfos();
this指的是stu对象
3.作为构造函数调用(this指向创建的对象)
function constr(){
this.m = 10;
}
var newObj = new constr();
console.info(newObj.m);
this指向newObj
4.Apply调用
var name = 'admin-g';
var age = 30;
var stu = {
name:'admin',
age:20,
getStuInfos:function(){
console.info(this.name+": "+this.age);
}
}
stu.getStuInfos.apply();//admin-g : 30 --不指定参数,this表示全局
this指的stu,但是由于apply,this还是指向window