javascript - 事件函數(shù)中this指向
問(wèn)題描述
<!DOCTYPE HTML><html lang='en-US'><head> <meta charset='UTF-8'> <title></title></head><body><h2 onmousedown = 'f1(this)'>事件中的this</h2> <script type='text/javascript'>var h2 = document.getElementsByTagName(’h2’)[0];//HTML方式綁定function f1(obj){ console.log(obj);}f1( this );/*//DOM 0級(jí)綁定方式h2.onclick = function(){ console.log(this);}//DOM 2級(jí)方式h2.addEventListener(’mouseover’,function(){ console.log(this);});*/ </script> </body></html>
問(wèn)題解答
回答1:javascript的this跟函數(shù)定義在哪里無(wú)關(guān),跟誰(shuí)調(diào)用它有關(guān)。
回答2:h2那里因?yàn)槭墙壎ㄔ谑录系模虼?this 指向的是這個(gè)元素,你可以簡(jiǎn)單理解為是
var dom = document.getElementsByTagName(’h2’)dom.onmousedown = function(){ f1(this)}回答3:
http://www.cnblogs.com/soulii...看看這個(gè)
回答4:前者相當(dāng)于`請(qǐng)輸入代碼
var h2 = document.querySelectorAll('h2')[0];function fn(){ console.log(this);}h2.onmousedown = fn;window.fn();
this指向調(diào)用它的對(duì)象,你定義在全局環(huán)境里的變量和函數(shù)默認(rèn)是window對(duì)象下得屬性和方法,所以當(dāng)你在全局環(huán)境中執(zhí)行fn()時(shí)this指向window
回答5:你獲取到哪個(gè)dom,就是對(duì)應(yīng)的this。
回答6:這兩個(gè)不是一回事呀。
<h2 onmousedown='f1(this)'></h2>h2.onmouseover=f1()h2.addEventListern(f1)
這三種方式都是為h2綁定了一個(gè)mouseover事件發(fā)生時(shí)的名為f1回調(diào)函數(shù),事件綁定的回調(diào)函數(shù)指向DOM元素本身。
你問(wèn)題中的
//HTML方式綁定function f1(obj){ console.log(obj);}f1( this );
這段程序是在window作用域下運(yùn)行的,this自然就指向window。這段代碼跟h2無(wú)關(guān)了(未綁定)。
相關(guān)文章:
1. angular.js - angularjs的自定義過(guò)濾器如何給文字加顏色?2. dockerfile - 為什么docker容器啟動(dòng)不了?3. 請(qǐng)教各位大佬,瀏覽器點(diǎn) 提交實(shí)例為什么沒(méi)有反應(yīng)4. javascript - es6中this5. macos - mac下docker如何設(shè)置代理6. dockerfile - 我用docker build的時(shí)候出現(xiàn)下邊問(wèn)題 麻煩幫我看一下7. 新手 - Python 爬蟲 問(wèn)題 求助8. javascript - 用rem寫的頁(yè)面,安卓手機(jī)顯示文字是正常的,蘋果顯示的文字是特別小的是為什么呢9. mysql - AttributeError: ’module’ object has no attribute ’MatchType’10. javascript - 我的站點(diǎn)貌似被別人克隆了, google 搜索特定文章,除了域名不一樣,其他的都一樣,如何解決?
