javascript - Closures, closures, closures, still don't understand closures
高洛峰
高洛峰 2017-05-19 10:14:40
0
5
684

Closure Closure I still don’t understand. Seek to explain.

        var fwx = (function(){
            var i = 0;
            var a = 1;
            var b = 2;
            var c = function (m) {var a = m;
                 a = m;
                console.log(i++);
              //  i = null;
            };
            var d = function () {
                var v  = a;
                console.log("。。。。"+a);
                console.log(i++);

                console.log(this.i);
                return v;
            };

            return {
                i : i ,
                a : a ,
                c : c ,
                d : d
            }
        })();

        console.log(fwx.i+"+"+fwx.a,
                fwx.d()+"+"+fwx.i,
                fwx.d()+"+"+fwx.i,

                fwx.c(111)+"+"+fwx.i,

                fwx.d()+"+"+fwx.i,
                fwx.d()+"+"+fwx.i,
                fwx.d()+"+"+fwx.i,
                fwx.a
        );

1.The closure domain in method c contains a and i
So what is the difference between a and fwx.a?

2. How do I clear the closure?

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(5)
给我你的怀抱

Closure means that a function can access variables in the scope in which it is declared. According to this feature, a function can be returned within the function. Through this returned function, the variables in the function can be accessed outside the function;
According to the scope chain, when When a function accesses a variable, it first searches within its own scope. If not, it searches in the scope of the outer function, and so on, until the global scope is found. Because there is a in the c function scope, a and fwx in the c function a is different, and i is i in fwx

phpcn_u1582

Recommend an article about closures and understand closures through chrome developer tools.

phpcn_u1582

It doesn’t matter how many questions you do like this. Just do the project and you will understand as you do it.

phpcn_u1582

"Javascript You Don't Know" Read this book to understand it more deeply

某草草

I tend to agree with one statement: the front-end must be done step by step, and you cannot defeat monsters by leapfrogging.
You must have written some code and have some ideas of your own, and then you will understand it better after reading it. Before that, read more and write more, there is no other way.
I am from C++ background, and I was confused when I first read it. It took me more than a year to understand it from the beginning.
http://user.qzone.qq.com/2084...
The above is an article written by myself, combined with the answers of Ruan Yifeng and the previous answerer on Zhihu, as well as other blogs on the Internet A diary of , I hope it will be helpful to you

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template