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. docker容器呢SSH為什么連不通呢?2. docker - 如何修改運行中容器的配置3. 關docker hub上有些鏡像的tag被標記““This image has vulnerabilities””4. docker start -a dockername 老是卡住,什么情況?5. Android TextView 或 ListView 加載過渡效果6. docker - 各位電腦上有多少個容器啊?容器一多,自己都搞混了,咋辦呢?7. python - thrift 返回 TSocket read 0 bytes 求助!!!!8. python3.x - python中import theano出錯9. python - (初學者)代碼運行不起來,求指導,謝謝!10. python - django模板 include模板的數據問題
