How Javascript Closures Work

preview_player
Показать описание
Do you know how Javascript closures work?

Closures refer to local variables for a function that are still used after the function has been returned.

Then it is like a call back.

A call back is when one function refers to another, passing it forward like a variable. You could look at it a little like class inheritance.

Class inheritance is closer to a Venn diagram, with the function having a set of properties it gets from the parent. Closures are like a smaller subset staying in use after the larger circle is removed.

Programmers who worked in functional programming instead of object oriented programming think about functions as pointers to a function. JavaScript references a function instead of pointing it but you can put in a hidden pointer to a closure as well.

I'm lost.

Closures can be referred to as a stack frame that isn't de-allocated when the function returns. Or it can be a function you treat like a variable that can be a pointer, too, like traditional code did.

How do closures work?

A line of code is a closure because it has an anonymous function declared inside of another function.

So just by declaring a function inside of another function, I create a closure. I'm glad I have closure on that.

When you do this, the local variables are accessible even after you return to the function that was just called.

Please do not return to the prior examples that did not explain the concept.

When you use a closure in JavaScript, the anonymous function is able to reference text containing a value because it retains the local variables kept within the closure.

So the outside function can run the inner function, and the inner function can still access variables used by the outer one. That's a little like embedded code.

But it is all inside of the same JavaScript code.
Рекомендации по теме