On the closure of javascript

  • 2021-07-13 04:18:07
  • OfStack

On the Explanation of Closure

We describe the scope chain as a list of objects, not a bound stack. Every time you call the javascript function, you create a new object to hold the variable, add this object to the scope, and when the function returns, you delete the object bound to the variable from the scope chain. If there is no nested function and no other reference points to the bound object, it will be garbage collected.


 (function () {
 var val = null;
 var callback;
 setTimeout(function () {
  val = 1;
  callback(val)
 },1000)
 window.getVal = function(fn){
  callback = fn;
 }
 })();
 (function(){
 var b =3;
 getVal(function (val) {
  console.log(val);//1
  console.log(b); //3
 getVal(function (val) {
 console.log(val);
 console.log(b); // Why can you still print out here b What about this variable /. 
 });
 // The anonymous function here is actually 1 Closure, you are equivalent to passing through getVal The function passed this closure. Think about it. Is the closure like this? 
})();
//2 Scope 
 (function(){
 var b =3;
 var ret = function (val) {
  console.log(val);

Access Method of Private Attributes Using Closure


 function c     
  return {
  count:function(){
  return n++;
  }
  };
  }
 var a=counter();
 alert(a.count());// Returned 0 ; 
 alert(a.count());// Returns the 1 ; 

Private property method implemented by the closure defined by


function addPrivateProperty ( o , name , predicate ) {
var value;
o["get"+name]=function(){return value);}//get  The properties of the accessor are read-only , Return it directly and simply 
//setter Method verifies that the value is legal, and if it is illegal, throws an exception 
o["set"+name]=function(v){{
if(predicate&&!predicate(v)) throw Error("");
else {
value=v;
}
}

Typical error


function constfuncs(){
var funcs=[];
for(var i=0;i<10;i++){
funcs[i]=function(){return i;};
}
return funcs;
}
var func=constfuncs();
console.log(func[5]());
;// Return value ? 10

Since the closures of this function are all defined in the same function call, the variable i; can be shared;

Scope chains associated with closures are all active, and nested functions do not copy one private member in scope, nor do they generate static snapshots of bound variables; When closing, this is a keyword of javascript instead of a variable

Solution


function Bb(){
this.run=function(){}//this Is Bb This object; 
}
 And function run(){
function gg(){alert(this Is window)}//this Is window;`
}

Related articles: