javascript - 事件函數中this指向
問題描述
<!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級綁定方式h2.onclick = function(){ console.log(this);}//DOM 2級方式h2.addEventListener(’mouseover’,function(){ console.log(this);});*/ </script> </body></html>
問題解答
回答1:javascript的this跟函數定義在哪里無關,跟誰調用它有關。
回答2:h2那里因為是綁定在事件上的,因此 this 指向的是這個元素,你可以簡單理解為是
var dom = document.getElementsByTagName(’h2’)dom.onmousedown = function(){ f1(this)}回答3:
http://www.cnblogs.com/soulii...看看這個
回答4:前者相當于`請輸入代碼
var h2 = document.querySelectorAll('h2')[0];function fn(){ console.log(this);}h2.onmousedown = fn;window.fn();
this指向調用它的對象,你定義在全局環境里的變量和函數默認是window對象下得屬性和方法,所以當你在全局環境中執行fn()時this指向window
回答5:你獲取到哪個dom,就是對應的this。
回答6:這兩個不是一回事呀。
<h2 onmousedown='f1(this)'></h2>h2.onmouseover=f1()h2.addEventListern(f1)
這三種方式都是為h2綁定了一個mouseover事件發生時的名為f1回調函數,事件綁定的回調函數指向DOM元素本身。
你問題中的
//HTML方式綁定function f1(obj){ console.log(obj);}f1( this );
這段程序是在window作用域下運行的,this自然就指向window。這段代碼跟h2無關了(未綁定)。
相關文章:
1. mysql - AttributeError: ’module’ object has no attribute ’MatchType’2. python - from ..xxxx import xxxx到底是什么意思呢?3. 求大神幫我看看是哪里寫錯了 感謝細心解答4. npm鏡像站全新上線5. javascript - 圖片能在網站顯示,但控制臺仍舊報錯403 (Forbidden)6. 網頁爬蟲 - python爬蟲翻頁問題,請問各位大神我這段代碼怎樣翻頁,還有價格要登陸后才能看到,應該怎么解決7. php自學從哪里開始?8. MySQL客戶端吃掉了SQL注解?9. phpstady在win10上運行10. 數據庫 - MySQL 單表500W+數據,查詢超時,如何優化呢?
