简体   繁体   中英

Why does an anonymous function have access to a variable from the function it is defined in?

I'm trying to get my head around jQuery and JavaScript objects and functions and grasp how this works and where it points to.

Please can someone explain why this works.

Cat.prototype.meowLater = function() {
    var self = this;
    window.setTimeout(
        function() {
            self.meow();
        }
        , 1000);
}

The bit I'm interested in and confused by is why the variable self can actually be accessed in the anonymous function that's called by the timer. I thought that because self is declared in another function that it would be local and only accessible to that function.

A function inherits variables from the parent scope (unless masked by another variable with the same name and of narrower scope).

Since the anonymous function is defined inside the function to which self is scoped, it has access to it.

Inner functions can use variables available to outer functions.

Here,

Cat.prototype.meowLater = function() {
    // I create the variable self that refers to the this (the current object)
    var self = this;

    // I create a timeout that calls the self.meow function within an anonymous function
    /*** NOTE : You don’t always have to create an anonymous function it’s just that in
        this case, it is required ***/
    window.setTimeout(
        function() {
            self.meow();
        }
        , 1000);
}

Since, the setTimeout is inner function of Cat.prototype.meowLater , self available to setTimeout .

Also,
we are not using this.meow() here, because this refers to current object , thus to window in setTimeout function.

Javascript has nested scopes, so a function inside of another function inherits all the variables from the outer function (it's still in scope). When you use async functions ( setTimeout in this case) the variable self will refer to the scoped self variable, which is this (a Cat instance), but this will be window.

Hopefully that helps, it's something that takes some time to get used to.

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