this points to this in summary 1 dom event binding

Who does this point to in this1 event binding

Traditional binding 1 Event binding behind the label
  1. html code:
    <button id="btn" onclick="test()">按钮</button>
    
    js code
    function test() {
          
          
       console.log(this)
    }
    
    Click the button to print the result as a window object
  2. html code
    <button id="btn" onclick="test(this)">按钮</button>
    
    js code
    function test() {
          
          
       console.log(this)
    }
    
    After clicking the button, the print result is the button dom node
Other traditional binding
//1. 有名函数绑定
document.getElementById('btn').onclick=test
function test() {
    
    
   console.log(this)
}
//2.匿名函数绑定
document.getElementById('btn').onclick=function() {
    
    
	console.log(this)//或者 test()
}

After clicking the button, the print result is the button dom node

Modern binding
//1. 有名函数绑定
document.getElementById('btn').addEventListener('click',test,false)
function test() {
    
    
   console.log(this)
}
//2.匿名函数绑定
document.getElementById('btn').addEventListener('click',function(){
    
    
	console.log(this)//或者 test()
},false)

After clicking the button, the print result is the button dom node

Summary: In event binding, as long as the event is bound through the dom node, this points to the dom node

If the event is bound in the label and this is not passed in the method, the this in the function points to window, and if this is passed, this points to the dom node

Guess you like

Origin blog.csdn.net/Chennfengg222/article/details/104690327