有人能告诉我为什么当我获得变量myBrand directy时,我最终会得到默认值吗?我只是在玩闭包,并试图对返回做一些不同的事情,基本上没有把它放进去,这给了我开始时的默认值
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
包含创建对象时myBrand
的值的副本。
它不包含对变量的引用,因此当您更改变量的值时,不会更改getBrandSimple
的值。