this的指向在函數(shù)定義的時(shí)候是無法確定的,只有函數(shù)執(zhí)行的時(shí)候才能確定this到底指向誰,實(shí)際this指向是調(diào)用他的對(duì)象麸锉。
1.栗子1
function a(){
var user = "小瑩瑩";
console.log(this.user);//undefined
console.log(this);//window
}
a();
// 等同于windiw.a()實(shí)際為window調(diào)用烂瘫,還有alert()方法也是window對(duì)象
2.栗子2
var obj = {
user:"小瑩瑩",
fn:function(){
console.log(this.user);//小瑩瑩this指向是obj
}
}
obj.fn();
3.栗子3
var obj = {
a:10,
b:{
a:12,
fn:function(){
console.log(this.a);//12
}
}
}
o.b.fn();
4.栗子4
var obj = {
a:10,
b:{
//a:12,
fn:function(){
console.log(this.a);//undefined
}
}
}
o.b.fn
當(dāng)函數(shù)中包含多個(gè)對(duì)象時(shí),this指向上一級(jí)的對(duì)象
5.栗子5
var obj = {
a:10,
b:{
a:12,
fn:function(){
console.log(this.a);//undefined
console.log(this);//window
}
}
}
var j = o.b.fn;//o.b.fn賦給j時(shí)沒有執(zhí)行胳施,只有方法,這時(shí)this已經(jīng)指向window
j();
總結(jié):
- 當(dāng)使用fn()或者定義新對(duì)象賦給fn方法 var j =o.fn肢专,this指向是window,alert()方法調(diào)用時(shí)window
- 當(dāng)對(duì)象直接調(diào)用方法時(shí)舞肆,obj.fn(),this指向當(dāng)前調(diào)用的對(duì)象
- 當(dāng)函數(shù)調(diào)用時(shí)包含多個(gè)對(duì)象的時(shí)候,this指向上一級(jí)的對(duì)象博杖,沒有上一級(jí)對(duì)象為undefined