大家都知道this在英文中就是指代词,在英文中this指的是主人公,但是在javascript中就没有那么简单,它在不同的地方会指代不同,总结起来有以下四种情况。
1. 函数预编译过程this——>window
function test(){
var a= 123;
function b(){}
}
//预编译
AO{
arguments:[1],
this:window,
c:1;
a:underfined,
b:function(){}
}
test(1);
2. 全局作用域 this——>window
3. call/apply可以改变函数运行时this指向
function Person(age,name){
<!--this发生改变指向了obj-->
this.name = name;
this.age = age;
}
var person = new Person('deng',100);
var obj = {} Person.call(obj,'cheng',300);
4. obj.func(); func()里面this指向obj
var obj = {
a:function(){
console.log(this.name)
<!-- 谁调用a,this就代表谁 ,这里的this就代表obj-->
},
name:'abc' ;
}
obj.a();
下面这段代码就可以很好的检验我们自己对于this指代问题有没有掌握
var name = '222';
var a = {
name:"111",
say:function(){
console.log(this.name);
}
}
var fun = a.say;
fun();
//输出222 全局执行
a.say();
//输出111
var b ={
name:"333",
say:function(fun){
fun();
//222(没有人调用它,那就是预编译,此时的this指向window)
}
}
b.say(a.say);
//所以在这里输出的是全局变量222
b.say = a.say;
b.say();
//输出333
这就是在JavaScript中this指代的四种不同情况。