JavaScript closure example

  • 2020-03-30 02:43:46
  • OfStack

The benefit of this is that internal functions can access the arguments and variables of the external functions that define them.

First, let's construct a simple object.


var testObj = {
    value: 10,
    add: function(inc){
        this.value += (typeof inc === "number") ? inc : 1;
    }
};
testObj.add();
testObj.value; // 11
testObj.add(2);    
testObj.value; // 13

There is a problem with this. The value cannot be guaranteed not to be illegally modified, so it can be modified in the following way.

var testObj = (function(){
    var value = 10;
    return {
        add: function(inc){
            value += (typeof inc === "number") ? inc : 1;
        },
        getValue: function(){
            return value;
        }
    };
})();
testObj.add();
testObj.getValue(); // 11
testObj.add(2);
testObj.getValue(); // 13

We can initialize testObj in the form of a generic call to a function that returns an object literal, which defines a value variable that is always available to the add and getValue methods, but whose scope makes it invisible to other programs. At the same time, we can also conclude that the inner function has a longer lifetime than its outer function.

Let's continue with an example of a constructor call.


var MyObj = function(str){
    this.status = str;
};
MyObj.prototype.getStatus = function(){
    return this.status;
};
var obj = new MyObj("javascript");
obj.getStatus(); // "javascript"

There's nothing wrong with writing this, but it's a bit of an "unnecessary step", so why use a getStatus method to access a property that could have been accessed directly? Of course it makes sense if status is private.

var obj = function(status){
    return {
        getStatus: function(){
            return status;
        }
    };
};
var myObj = obj("javascript");
myObj.getStatus(); // "javascript"

Here, when we call obj, it returns a new object containing the getStatus method, a reference to which is stored in myObj, and even though obj has returned, the getStatus method still has the privilege of accessing the status attribute of the obj object. Instead of accessing a copy of the parameter, the getStatus method accesses the parameter itself. This is possible because the function can access the context in which it was created, which is called a closure.


Related articles: