search

Home  >  Q&A  >  body text

javascript - Why does getValue() return 123?

    var getValue,setValue;
    (function(){
      var secret=0;
      getValue=function(){
        return secret;
      };
      setValue=function(v){
        if(typeof v==="number"){
          secret=v;
      }
    };
  }());
  
  getValue();//0
  
  setValue(123);
  getValue();//123
        
  setValue(false);
  getValue();//123
伊谢尔伦伊谢尔伦2819 days ago683

reply all(2)I'll reply

  • 世界只因有你

    世界只因有你2017-06-26 10:59:34

    getValue() and setValue() are closures, sharing a variable secret, so if the secret is changed in the setValue function, getValue() will of course read the secret Change accordingly.

    reply
    0
  • 淡淡烟草味

    淡淡烟草味2017-06-26 10:59:34

    Isn’t it 0? How did you get 123.

    reply
    0
  • Cancelreply