【发布时间】: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