简体   繁体   English

Javascript 闭包和变量

[英]Javascript closures and variables

Can any one tell me why when i get the variable myBrand directy I end up with the default value?谁能告诉我为什么当我直接获得变量 myBrand 时我最终得到默认值? I was just playing with closures and tryed to do something different with the return, basically not puting it in, which gives me the default value that was at the begining我只是在玩闭包并尝试对返回做一些不同的事情,基本上没有把它放进去,这给了我一开始的默认值

const car = ()=>{
   let myBrand = 'generic' //default value
   function printbrand(){console.log(myBrand)}
   return{
    setBrand: (newBrand)=>{myBrand = newBrand},
    getBrand: ()=>{return myBrand},
    getBrandSimple: myBrand,
    usePrinter: ()=> {return printbrand()},
   }
}

var myCar = car()
myCar.setBrand('tesla')
console.log(`Brand with direct = ${myCar.getBrandSimple}`)
     //Output
    // Brand with direct = generic
console.log(`Brand with function = ${myCar.getBrand()}`);
    //Output
   // Brand with function = tesla
console.log(`Brand with printer = `);
myCar.usePrinter()
    //Output
   // Brand with printer = 
  // tesla
console.log(`Brand with direct = ${myCar.getBrandSimple}`)
   //Output
  // Brand with direct = generic

getBrandSimple contains a copy of the value of myBrand at the time the object is created . getBrandSimple包含创建myBrandmyBrand副本

It doesn't contain a reference to the variable so when you change the value of the variable, you don't change the value of getBrandSimple .它不包含对变量的引用,因此当您更改变量的值时,您不会更改getBrandSimple的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM