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. java - spring-security與微信登錄的問題?2. MySQL啟動錯誤3. html5 - iphone5手機,微信中無法打開優酷鏈接?4. html5和Flash對抗是什么情況?5. android-studio - android studio 結巴了,有什么辦法可以治好它嗎?6. docker gitlab 如何git clone?7. docker-compose 為何找不到配置文件?8. 前端 - ng-view不能加載進模板9. javascript - angularjs怎么獲取repeat里的某些$index值?10. javascript - 求解答:實例對象調用constructor,此時constructor內的this的指向?
