JavaScript Closures 101: What is a closure?




A JavaScript closure is a function that has a pointer reference to a free variable. A free variable is one that has fallen out of scope after its parent function has returned. However, if that outer function still has some reference to the free var (normally through a function that gets returned, or through a method property), the variable will not get garbage collected because it will have a non-zero reference count. Thus, from outside the function, we can still access the inner variable by means of the closure.

Copyright (c) 2013 Rodrigo Silveira http://www.easylearntutorial.com

Original source


44 responses to “JavaScript Closures 101: What is a closure?”

  1. THANK YOU! The first time I ever saw someone name the PARAMETER and VARIABLE differently "just to make things clear"… which is very wise. Many docs and explanations seem to think they are being clever by using the same names.

  2. I watched this video because I was trying to understand the idea of anonymous classes having closure in Java (not JavaScript) and I thought hat the concepts might translate.
    This doesn't seem different from a standard 'getter' function to expose private fields in a class. If the excitement that the getter is attached to a function, not to a class? I've seen JavaScript patterns like Revealing Module Pattern to simulate OOP in JavaScript except using functions instead of classes.

  3. I don't undersand why I got different in the final example .I type these in my chrome
    function Person(name) {
    var _name = name;
    this.getName = function(){
    return _name;
    };
    }
    var me = new Person("Mihai");
    but I got Person{};without name;

Leave a Reply