简体   繁体   中英

Why does wrapping a callback in an anonymous function change the meaning of 'this'?

If I have a method that uses the keyword this :

let myObject = {
    logThis: function(){
        console.log(this)
    },
}

And I pass it to a higherOrder function:

function higherOrder(callback){
    callback()
}

higherOrder(obj.logThis)

this will not refer to myObject , but to the object that calls higherOrder (in this case, the window object). I understand that this is because its execution context changes.

what I dont understand is why when I wrap it in an anonymous function like this:

higherOrder(function(){myObject.logThis()})

this will again refer to myObject . Isn't the execution context still changing?
If i'm passing it to a function that exists in the global scope, shouldn't this refer to the global scope?
I can't figure out why wrapping it in an anonymous function should change anything.

Using an anonymous function wraps MyObj in a closure. That closure's lexical scope (execution context) is now localized to the closure. So this is localized to the closure (and MyObj) as well.

You can discover that by using a debugger with a break point set on the callback() call.

This image shows the variable structure with the closure in place:

使用匿名函数包装器

Without the function wrapper, the lexical scope is the same scope as the higherOrder() function - which is the global scope. Again, this is demonstrated with a break point on the same line of code (note lack of closure):

无包装

Note: this code is run in node - so no Window object here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM