關(guān)于js里的this關(guān)鍵字的理解
this關(guān)鍵字在c++,java中都提供了這個(gè)關(guān)鍵字,在剛開始學(xué)習(xí)時(shí)覺得有難度,但是只要理解了,用起來(lái)就方便多了,下面通過(guò)本篇文章給大家詳解js里this關(guān)鍵字的理解。
關(guān)于this,是很多前端面試必考的題目,有時(shí)候在網(wǎng)上看到這些題目,自己試了一下,額,還真的錯(cuò)了!在實(shí)際開發(fā)中,也會(huì)遇到 this 的問(wèn)題(雖然一些類庫(kù)會(huì)幫我們處理),例如在使用一些框架的時(shí)候,例如:knockout,有時(shí)候不明白為什么不直接使用this,而要把 this 作為參數(shù)傳入。
接下來(lái)你談?wù)勎覍?duì)它的理解,也作為一個(gè)筆記,方便以后參閱。有不對(duì)的地方,歡迎指出批評(píng)。
1. 不像C#,this一定是指向當(dāng)前對(duì)象。
js的this指向是不確定的,也就是說(shuō)是可以動(dòng)態(tài)改變的。call/apply 就是用于改變this指向的函數(shù),這樣設(shè)計(jì)可以讓代碼更加靈活,復(fù)用性更高。
2. this 一般情況下,都是指向函數(shù)的擁有者。
這一點(diǎn)很重要!這一點(diǎn)很重要!這一點(diǎn)很重要!
這也是一道常見的面試題,如下代碼:
<script type="text/javascript">
var number = 1;
var obj = {
number: 2,
showNumber: function(){
this.number = 3;
(function(){
console.log(this.number);
})();
console.log(this.number);
}
};
obj.showNumber();
</script>
由于showNumber方法的擁有者是obj,所以this.number=3; this 指向的就是 obj 的屬性 number。
同理,第二個(gè) console.log 打印的也是屬性 number。
為什么第二點(diǎn)說(shuō)一般情況下this都是指向函數(shù)的擁有者,因?yàn)橛刑厥馇闆r。函數(shù)自執(zhí)行就是特殊情況,在函數(shù)自執(zhí)行里,this 指向的是:window。所以第一個(gè) console.log 打印的是 window 的屬性 number。
所以要加一點(diǎn):
3. 在函數(shù)自執(zhí)行里,this 指向的是 window 對(duì)象。
擴(kuò)展,關(guān)于this,還有一個(gè)地方比較讓人模糊的是在 dom 事件里,通常有如下3種情況:
如下:
1. 使用標(biāo)簽屬性注冊(cè)事件,此時(shí)this 指向的是 window 對(duì)象。
<input id="test" type="button" value="按鈕" onClick="test()"/>
function test(){alert(this)}
2. 對(duì)于1,要讓 this 指向 input,可以將 this 作為參數(shù)傳遞。
3. 使用 addEventListener 等注冊(cè)。此時(shí)this 也是指向 input。
document.getElementById("test").addEventListener("click",test);
在面向?qū)ο缶幊陶Z(yǔ)言中,對(duì)于this關(guān)鍵字我們是非常熟悉的。比如C++、C#和Java等都提供了這個(gè)關(guān)鍵字,雖然在開始學(xué)習(xí)的時(shí)候覺得比較難,但只要理解了,用起來(lái)是非常方便和意義確定的。JavaScript也提供了這個(gè)this關(guān)鍵字,不過(guò)用起來(lái)就比經(jīng)典OO語(yǔ)言中要"混亂"的多了。
下面就來(lái)看看,在JavaScript中各種this的使用方法有什么混亂之處?
1、在HTML元素事件屬性中inline方式使用this關(guān)鍵字:
// 可以在里面使用this ">division element // 可以在里面使用this ">division element
我們一般比較常用的方法是在此使用:javascirpt: EventHandler(this),這樣的形式。不過(guò)這里其實(shí)可以寫任何合法的JavaScript語(yǔ)句,要是高興在此定義個(gè)類也可以(不過(guò)將會(huì)是個(gè)內(nèi)部類)。這里的原理是腳本引擎生成了一個(gè)div實(shí)例對(duì)象的匿名成員方法,而onclick指向這個(gè)方法。
2、用DOM方式在事件處理函數(shù)中使用this關(guān)鍵字:
division element
var div = document.getElementById('elmtDiv');
div.attachEvent('onclick', EventHandler);
function EventHandler()
{
// 在此使用this
}
// -->
division element
var div = document.getElementById('elmtDiv');
div.attachEvent('onclick', EventHandler);
function EventHandler()
{
// 在此使用this
}
// -->
這時(shí)的EventHandler()方法中的this關(guān)鍵字,指示的對(duì)象是IE的window對(duì)象。這是因?yàn)镋ventHandler只是一個(gè)普通的函數(shù),對(duì)于attachEvent后,腳本引擎對(duì)它的調(diào)用和div對(duì)象本身沒(méi)有任何的關(guān)系。同時(shí)你可以再看看EventHandler的caller屬性,它是等于null的。如果我們要在這個(gè)方法中獲得div對(duì)象引用,應(yīng)該使用:this.event.srcElement。
3、用DHTML方式在事件處理函數(shù)中使用this關(guān)鍵字:
division element
lt;mce:script language="javascript">
var div = document.getElementById('elmtDiv');
div.onclick = function()
{
// 在此使用this
};
/ -->
division element
var div = document.getElementById('elmtDiv');
div.onclick = function()
{
// 在此使用this
};
// -->
這里的this關(guān)鍵字指示的內(nèi)容是div元素對(duì)象實(shí)例,在腳本中使用DHTML方式直接為div.onclick賦值一個(gè)EventHandler的方法,等于為div對(duì)象實(shí)例添加一個(gè)成員方法。這種方式和第一種方法的區(qū)別是,第一種方法是使用HTML方式,而這里是DHTML方式,后者腳本解析引擎不會(huì)再生成匿名方法。
4、類定義中使用this關(guān)鍵字:
function JSClass()
{
var myName = 'jsclass';
this.m_Name = 'JSClass';
}
JSClass.prototype.ToString = function()
{
alert(myName + ', ' + this.m_Name);
};
var jc = new JSClass();
jc.ToString();
function JSClass()
{
var myName = 'jsclass';
this.m_Name = 'JSClass';
}
JSClass.prototype.ToString = function()
{
alert(myName + ', ' + this.m_Name);
};
var jc = new JSClass();
jc.ToString();
這是JavaScript模擬類定義中對(duì)this的使用,這個(gè)和其它的OO語(yǔ)言中的情況非常的相識(shí)。但是這里要求成員屬性和方法必須使用this關(guān)鍵字來(lái)引用,運(yùn)行上面的程序會(huì)被告知myName未定義。
5、為腳本引擎內(nèi)部對(duì)象添加原形方法中的this關(guān)鍵字:
function.prototype.GetName = function()
{
var fnName = this.toString();
fnName = fnName.substr(0, fnName.indexOf('('));
fnName = fnName.replace(/^function/, '');
return fnName.replace(/(^\s+)|(\s+$)/g, '');
}
function foo(){}
alert(foo.GetName());
function.prototype.GetName = function()
{
var fnName = this.toString();
fnName = fnName.substr(0, fnName.indexOf('('));
fnName = fnName.replace(/^function/, '');
return fnName.replace(/(^\s+)|(\s+$)/g, '');
}
function foo(){}
alert(foo.GetName());
這里的this指代的是被添加原形的類的實(shí)例,和4中類定義有些相似,沒(méi)有什么太特別的地方。
6、結(jié)合2&4,說(shuō)一個(gè)比較迷惑的this關(guān)鍵字使用:
view plaincopy to clipboardprint?
function JSClass()
{
this.m_Text = 'division element';
this.m_Element = document.createElement('DIV');
this.m_Element.innerHTML = this.m_Text;
this.m_Element.attachEvent('onclick', this.ToString);
}
JSClass.prototype.Render = function()
{
document.body.appendChild(this.m_Element);
}
JSClass.prototype.ToString = function()
{
alert(this.m_Text);
};
var jc = new JSClass();
jc.Render();
jc.ToString();
function JSClass()
{
this.m_Text = 'division element';
this.m_Element = document.createElement('DIV');
this.m_Element.innerHTML = this.m_Text;
this.m_Element.attachEvent('onclick', this.ToString);
}
JSClass.prototype.Render = function()
{
document.body.appendChild(this.m_Element);
}
JSClass.prototype.ToString = function()
{
alert(this.m_Text);
};
var jc = new JSClass();
jc.Render();
jc.ToString();
我就說(shuō)說(shuō)結(jié)果,頁(yè)面運(yùn)行后會(huì)顯示:"division element",確定后點(diǎn)擊文字"division element",將會(huì)顯示:"undefined"。
7、CSS的expression表達(dá)式中使用this關(guān)鍵字:
height: expression(this.parentElement.height);"> division element height: expression(this.parentElement.height);"> division element
這里的this看作和1中的一樣就可以了,它也是指代div元素對(duì)象實(shí)例本身。
8、函數(shù)中的內(nèi)部函數(shù)中使用this關(guān)鍵字:
view plaincopy to clipboardprint?
function OuterFoo()
{
this.Name = 'Outer Name';
function InnerFoo()
{
var Name = 'Inner Name';
alert(Name + ', ' + this.Name);
}
return InnerFoo;
}
OuterFoo()();
function OuterFoo()
{
this.Name = 'Outer Name';
function InnerFoo()
{
var Name = 'Inner Name';
alert(Name + ', ' + this.Name);
}
return InnerFoo;
}
OuterFoo()();
運(yùn)行結(jié)果顯示是:"Inner Name, Outer Name"。按我們?cè)?中的講解,這里的結(jié)果如果是"Inner Name, undefined"似乎更合理些吧?但是正確的結(jié)果確實(shí)是前者,這是由于JavaScript變量作用域的問(wèn)題決定的,詳細(xì)了解推薦參看"原來(lái)JScript中的關(guān)鍵字'var'還是有文章的"一文及回復(fù)。
歸納起來(lái),JavaScript中的this用法有以下3種(詳細(xì)用法參原文):
1.在HTML元素事件屬性 或 CSS的expression表達(dá)式 中inline方式使用this關(guān)鍵字——對(duì)應(yīng)原文的1、7
2.在事件處理函數(shù)中使用this關(guān)鍵字——對(duì)應(yīng)原文的2、3
其中可分為兩種方式
(1)DOM方式——此種方式的結(jié)果是this指向窗口(window)對(duì)象
(2)DHTML方式——此種方式的結(jié)果是this指向div元素對(duì)象實(shí)例
3.在類定義中使用this關(guān)鍵字并在其 內(nèi)部函數(shù) 或 成員函數(shù)(主要是prototype產(chǎn)生)中使用——對(duì)應(yīng)原文的4、5、8
需要說(shuō)明的是,在函數(shù)也是個(gè)對(duì)象,因此需要區(qū)分 變量定義 和 成員變量定義,如下:
view plaincopy to clipboardprint? var variableName; //變量定義 //作用域:函數(shù)定義范圍內(nèi) //使用方法:直接使用variableName this.varName; //成員變量定義 //作用域:函數(shù)對(duì)象定義范圍內(nèi)及其成員函數(shù)中 //使用方法:this.varName var variableName; //變量定義 //作用域:函數(shù)定義范圍內(nèi) //使用方法:直接使用variableName this.varName; //成員變量定義 //作用域:函數(shù)對(duì)象定義范圍內(nèi)及其成員函數(shù)中 //使用方法:this.varName
以上歸納出的三類this的使用方法中,第一種比較容易理解,這里對(duì)原文中第6點(diǎn)提到的程序進(jìn)行了測(cè)試和改進(jìn)如下,以說(shuō)明上述后兩種使用方法:
view plaincopy to clipboardprint?
function JSClass()
{
var varText = "func variable!"; //函數(shù)中的普通變量
this.m_Text = 'func member!'; //函數(shù)類的成員變量
this.m_Element = document.createElement('DIV'); //成員變量,創(chuàng)建一個(gè)div對(duì)象
this.m_Element.innerHTML = varText; //使用函數(shù)的普通變量
this.m_Element.attachEvent('onclick', this.ToString); //給這個(gè)對(duì)象的事件連上處理函數(shù)
this.newElement = document.createElement('DIV');
this.newElement.innerHTML = "new element";
this.newElement.m_Text = "new element text!"; //給創(chuàng)建的對(duì)象建個(gè)成員
this.newElement.onclick = function()
{
alert(this.m_Text); //指向div對(duì)象的成員
};
}
JSClass.prototype.Render = function()
{
document.body.appendChild(this.m_Element); //把div對(duì)象掛在窗口上
document.body.appendChild(this.newElement);
}
JSClass.prototype.ToString = function()
{
alert(this.m_Text); //指向窗口(window)對(duì)象
};
function initialize(){
var jc = new JSClass();
jc.Render();
jc.ToString(); //里面的this指向JSClass類的實(shí)例,里面有m_Text成員
}
// -->
initialize();
// -->
function JSClass()
{
var varText = "func variable!"; //函數(shù)中的普通變量
this.m_Text = 'func member!'; //函數(shù)類的成員變量
this.m_Element = document.createElement('DIV'); //成員變量,創(chuàng)建一個(gè)div對(duì)象
this.m_Element.innerHTML = varText; //使用函數(shù)的普通變量
this.m_Element.attachEvent('onclick', this.ToString); //給這個(gè)對(duì)象的事件連上處理函數(shù)
this.newElement = document.createElement('DIV');
this.newElement.innerHTML = "new element";
this.newElement.m_Text = "new element text!"; //給創(chuàng)建的對(duì)象建個(gè)成員
this.newElement.onclick = function()
{
alert(this.m_Text); //指向div對(duì)象的成員
};
}
JSClass.prototype.Render = function()
{
document.body.appendChild(this.m_Element); //把div對(duì)象掛在窗口上
document.body.appendChild(this.newElement);
}
JSClass.prototype.ToString = function()
{
alert(this.m_Text); //指向窗口(window)對(duì)象
};
function initialize(){
var jc = new JSClass();
jc.Render();
jc.ToString(); //里面的this指向JSClass類的實(shí)例,里面有m_Text成員
}
// -->
initialize();
// -->
上面的代碼執(zhí)行結(jié)果是:
頁(yè)面加載時(shí),彈出對(duì)話框,輸出func member!
頁(yè)面上顯示
func variable! new element
單擊func variable時(shí),彈出對(duì)話框,顯示undefined
——因?yàn)檫@時(shí)toString函數(shù)里的this指針指向window
單擊new element時(shí),彈出對(duì)話框顯示new element text!
——因?yàn)檫@時(shí)toString函數(shù)里的this指針指向div元素,而該元素已經(jīng)定義了m_Text成員(this.newElement.m_Text = "new element text!")
相關(guān)文章
js如何計(jì)算斐波那契數(shù)列第n項(xiàng)的值
這篇文章主要介紹了js如何計(jì)算斐波那契數(shù)列第n項(xiàng)的值問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-01-01
JS實(shí)現(xiàn)的仿淘寶交易倒計(jì)時(shí)效果
這篇文章主要介紹了JS實(shí)現(xiàn)的仿淘寶交易倒計(jì)時(shí)效果,涉及JavaScript針對(duì)時(shí)間與日期的動(dòng)態(tài)操作技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-11-11
使用JavaScript實(shí)現(xiàn)Java的List功能(實(shí)例講解)
使用JavaScript實(shí)現(xiàn)Java的List功能(實(shí)例講解)。需要的朋友可以過(guò)來(lái)參考下,希望對(duì)大家有所幫助2013-11-11
js倒計(jì)時(shí)簡(jiǎn)單實(shí)現(xiàn)代碼
這篇文章主要為大家詳細(xì)介紹了js倒計(jì)時(shí)簡(jiǎn)單實(shí)現(xiàn)代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-08-08
JS實(shí)現(xiàn)換膚功能的方法實(shí)例詳解
這篇文章主要介紹了JS實(shí)現(xiàn)換膚功能的方法,結(jié)合實(shí)例形式分析了javascript針對(duì)頁(yè)面元素屬性與樣式動(dòng)態(tài)操作相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2019-01-01
深入理解JavaScript的事件執(zhí)行機(jī)制
本文主要介紹了JavaScript的事件執(zhí)行機(jī)制,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-09-09
Javascript如何實(shí)現(xiàn)雙指控制圖片功能
這篇文章主要介紹了Javascript如何實(shí)現(xiàn)雙指控制圖片功能,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-02-02
javascript實(shí)現(xiàn)的文字加密解密
javascript實(shí)現(xiàn)的文字加密解密...2007-06-06
原生JavaScript生成GUID的實(shí)現(xiàn)示例
GUID(全局統(tǒng)一標(biāo)識(shí)符)是指在一臺(tái)機(jī)器上生成的數(shù)字,下面為大家介紹下原生JavaScript生成GUID的實(shí)現(xiàn),需要的朋友不要錯(cuò)過(guò)2014-09-09
bootstrap tooltips在 angularJS中的使用方法
這篇文章主要介紹了bootstrap tooltips在 angularJS中的使用 ,需要的朋友可以參考下2019-04-04

