今天去面試,再次被面試官要求解釋一下this的用法渴肉。但是很遺憾冗懦,我對(duì)this的理解只局限與把它當(dāng)成全局變量。因此仇祭,回來(lái)之后披蕉,決定亡羊補(bǔ)牢,搞清楚this的用法乌奇。
1.全局代碼中的this
alert(this); //window
2.普通函數(shù)中的this
function test(){ this.x = 2; }; test(); alert(x); //全局變量x=2
這里this指向了全局對(duì)象嚣艇,即window。在嚴(yán)格模式中华弓,則是undefined。
為了證明是全局變量的x困乒,將代碼更改如下:
var x = 1; funcion test(){ alert(this.x) ; } test(); alert(x); //全局變量x=1
3.作為對(duì)象的方法調(diào)用
var name = "clever coder"; var person = { name : "foocoder", hello : function(sth){ console.log(this.name + " says " + sth); } } person.hello("hello world");
輸出 foocoder says hello world寂屏。this指向person對(duì)象,即當(dāng)前對(duì)象。
4.對(duì)于對(duì)象方法的內(nèi)部函數(shù)
var name = "clever coder"; var person = { name : "foocoder", hello : function(sth){ var sayhello = function(sth) { console.log(this.name + " says " + sth); }; sayhello(sth); } } person.hello("hello world");//clever coder says hello world
在內(nèi)部函數(shù)中迁霎,this沒(méi)有按預(yù)想的綁定到外層函數(shù)對(duì)象上吱抚,而是綁定到了全局對(duì)象。這里普遍被認(rèn)為是JavaScript語(yǔ)言的設(shè)計(jì)錯(cuò)誤考廉,因?yàn)闆](méi)有人想讓內(nèi)部函數(shù)中的this指向全局對(duì)象秘豹。一般的處理方式是將this作為變量保存下來(lái),一般約定為that或者self:
var name = "clever coder"; var person = { name : "foocoder", hello : function(sth){ var that = this; var sayhello = function(sth) { console.log(that.name + " says " + sth); }; sayhello(sth); } } person.hello("hello world");//foocoder says hello world
5.對(duì)于構(gòu)造函數(shù)中的this
所謂構(gòu)造函數(shù)昌粤,就是通過(guò)這個(gè)函數(shù)生成一個(gè)新對(duì)象(object)既绕。這時(shí),this就是指這個(gè)新對(duì)象涮坐。
function test(){ this.x = 1; } var o = new test(); alert(o.x); // 1
運(yùn)行結(jié)果為1凄贩。為了表明這時(shí)this不是全局對(duì)象,對(duì)代碼做一些改變:
var x = 2; function test(){ this.x = 1; } var o = new test(); alert(x); //2
運(yùn)行結(jié)果為2袱讹,表明全局變量x的值根本沒(méi)變疲扎。
5.apply的應(yīng)用
apply()是函數(shù)對(duì)象的一個(gè)方法,它的作用是改變函數(shù)的調(diào)用對(duì)象捷雕,它的第一個(gè)參數(shù)就表示改變后的調(diào)用這個(gè)函數(shù)的對(duì)象椒丧。因此,this指的就是這第一個(gè)參數(shù)救巷。
var x = 0; function test(){ alert(this.x); } var o={}; o.x = 1; o.m = test; o.m.apply(); //0
apply()的參數(shù)為空時(shí)壶熏,默認(rèn)調(diào)用全局對(duì)象。因此征绸,這時(shí)的運(yùn)行結(jié)果為0久橙,證明this指的是全局對(duì)象。
如果把最后一行代碼修改為
o.m.apply(o); //1
運(yùn)行結(jié)果就變成了1管怠,證明了這時(shí)this代表的是對(duì)象o淆衷。