This pointing to the problem

<html>     
<body>         
<div id="div1"> div</div>
</body>     
<script> 
    window.id = "window"; 
    document.getElementById( "div1" ).onclick = function(){ 
            alert ( this.id );        // :"div1"         
            var callback = function(){
                         alert ( this.id );        // :"window"         
            }         
            callback();     
    }; 
</script> 
</html>

Why does the this of the callback function point to window,? isn"t it called in div-sharpdiv1? Very confused

Mar.03,2022

callback is a function call, where this dynamically points to the caller. There is no explicit caller for callback in the code, so the caller is implicitly represented as window. So this.id is window.id when you run the callback function.


remember, as long as the function name is directly added with (), there is nothing extra. In this form of call, the this in the function all points to the global object. Except for those with strict mode (strict mode) applied.

Menu