你們都知道this在英文中就是指代詞,在英文中this指的是主人公,可是在javascript中就沒有那麼簡單,它在不一樣的地方會指代不一樣,總結起來有如下四種狀況。javascript
1. 函數預編譯過程this——>windowjava
function test(){
app
var a= 123;
函數
function b(){}
this
}
code
//預編譯ip
AO{ 作用域
arguments:[1], io
this:window,console
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指代的四種不一樣狀況。