Home >Web Front-end >JS Tutorial >JavaScript closure analysis

JavaScript closure analysis

一个新手
一个新手Original
2017-09-26 10:27:581222browse

When I first came into contact with closures in js, I was confused. Later, I saw closures again by chance and then I decided to understand this thing. I also found a lot of explanations on the Internet. A relatively good resource, here I want to use the closure I learned to summarize.

Closure: Construct a function within the function, and then This function has the ability to access external function parameters and variables (except this and arguments), which means that all functions are closures. The life cycle of internal functions is longer than external functions.

Here is a little bit about the scope of js: JavaScript does not have block-level scope, only function scope.

function a() {
        var temp = 0;
    }

This temp is like a private variable of function a, which cannot be accessed externally, so one way to get the value of temp is to return temp; like this It is true that the value of temp is obtained, but there is no way to protect temp, so temp will be initialized every time you call a(), and the result of the previous execution of this function has already been released by GC.

Look at a piece of closure code:

function person() {
        var age = 10;
        function get_age() {
            return age+=1;
        }
        return get_age;
    }
    var temp = person();这是一个简单的闭包,在person函数里面构造了一个 get_age的函数,get_age这个函数可以访问person的所有参数和变量(除了this和arguments),并且最后把get_age作为了一个返回值返回.然后temp 的值为person调用的结果 所以temp的值就是get_age(),也就是说在person()中的get_age这个方法还在被使用中,所以GC不会释放person()和get_age()所占用的内存,简单来说:age这个参数不会被释放 会被保存下来.当调用:alert( temp() );alert( temp() );的时候 会输出11和12 也就是说 age = 10并没有被执行.闭包的注意点:既然GC不会回收,所以占用的内存是很大的外部函数的值改变时要注意 可能会影响到闭包中保存的总结: 因为在JavaScript中没有private私有变量的存在,所以想要达到这个效果 使用闭包是很不错的方法,同时可以用于一值保存函数中的变量,使其不会被GC所释放,GC不会自动释放活动的对象(在JavaScript中function也是对象).我想闭包既然是javascript中最好的特性之一,那么自然有他好的地方,具体的好个人认为 需要在实际开发中使用,用来积累经验.


The above is the detailed content of JavaScript closure analysis. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn