Questions that arise when studying js modular writing, the code is as follows
// 立即执行函数写法,保证外部不能访问到 count var module1 = (function() { var count = 0; var m1 = function() { return count; }; return { m1: m1 }; })(); // 如果现在想给 module1 添加新的方法 module1 = (function(mod) { mod.m2 = function() { return count; } return mod; })(module1); console.log(module1.m1());//可以访问到 count // console.log(module1.m2());
I want to know whymodule1.m2()
cannot accesscount
?
A clue: The reason why m1 can access count is because m1 and count are declared in the same function, that is, they are in the same scope, but the function where m2 is located is not in the same function as count. Under the scope, there is no relationship between functions embedded in functions, so naturally they cannot be accessed.
The questioner thinks that module1 itself is under the same function as count, so he adds a method to module1. This method is under the same scope as count?
Because of the lexical scope, JS functions have static scope, which means that when the function is defined, it has been determined what symbol the variable inside should be mounted to. When you define m1 internally, the anonymous function returns a count. This will be determined to be
var count=0
outside this function when it is defined.When you define m2, the anonymous function returns a count. The symbol search for this count is to first check whether it is inside the place where it is defined. If not, then check the place where the upper layer function is defined, and then the outermost place. It is a global variable, so the count here is a global variable.
So module1.m2() cannot access the count variable you defined at m1. Because of the static lexical scope, m2 cannot track it.