【问题标题】:Javascript closures and variablesJavascript 闭包和变量
【发布时间】:2021-04-28 16:32:51
【问题描述】:

谁能告诉我为什么当我直接获得变量 myBrand 时我最终得到默认值? 我只是在玩闭包并尝试对返回做一些不同的事情,基本上没有把它放进去,这给了我一开始的默认值

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

【问题讨论】:

    标签: javascript variables scope closures


    【解决方案1】:

    getBrandSimple 包含myBrand 在创建对象时的副本

    它不包含对变量的引用,因此当您更改变量的值时,您不会更改getBrandSimple 的值。

    【讨论】:

      猜你喜欢
      • 2011-01-19
      • 1970-01-01
      • 2015-07-06
      • 1970-01-01
      • 2011-08-22
      • 2021-10-16
      • 1970-01-01
      • 2016-04-30
      • 2014-01-13
      相关资源
      最近更新 更多