carlos mora
carlos mora

Reputation: 26

Javascript closures and variables

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

Upvotes: 0

Views: 30

Answers (1)

Quentin
Quentin

Reputation: 944556

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.

Upvotes: 1

Related Questions