javascript - this points to in the event function
欧阳克
欧阳克 2017-06-26 10:52:55
0
6
726

<!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>
欧阳克
欧阳克

温故而知新,可以为师矣。 博客:www.ouyangke.com

reply all(6)
为情所困

This in JavaScript has nothing to do with where the function is defined, but with who calls it.

小葫芦

h2 is bound to the event, so this points to this element. You can simply understand it as


var dom = document.getElementsByTagName('h2')
dom.onmousedown = function(){
    f1(this)
}
代言

http://www.cnblogs.com/soulii...Look at this

漂亮男人

The former is equivalent to `Please enter the code

var h2 = document.querySelectorAll("h2")[0];
function fn(){
    console.log(this);
}
h2.onmousedown = fn;
window.fn();

This points to the object that calls it. The variables and functions you define in the global environment default to the properties and methods of the window object, so when you execute fn() in the global environment, this points to window

代言

Which dom you get is the corresponding this.

洪涛

These two are not the same thing.

<h2 onmousedown="f1(this)"></h2>
h2.onmouseover=f1()
h2.addEventListern(f1)

These three methods all bind a callback function named f1 to h2 when the mouseover event occurs. The event-bound callback function points to the DOM element itself.

in your question
//HTML方式绑定
function f1(obj){
  console.log(obj);
}
f1( this );

This program runs under the window scope, so this naturally points to window. This code has nothing to do with h2 (unbound).

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template