0

Can any one tell me why when i get the variable myBrand directy I end up with the default value? 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
asked Apr 28, 2021 at 16:32

1 Answer 1

1

getBrandSimple contains a copy of the value of myBrand at the time the object is created.

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.

answered Apr 28, 2021 at 16:36
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.