Home > Mobile >  What is the correct syntax of JavaScript Factory Function? JavaScript Factory Function Syntax confus
What is the correct syntax of JavaScript Factory Function? JavaScript Factory Function Syntax confus

Time:05-19

Both function getMyCar1 & getMyCar2 has same result but which one is the correct way of doing?

getMycar2: Why value have to use instead of key? key:value (carBrand:brand).

function selectCar(brand, model, color){
    return{
        carBrand: brand,
        carModel: model,
        carColor: color, 

        getMyCar1: function(){
            return this.carBrand   " "   this.carModel   " "   this.carColor;  
         //It is said that no need this key word with factory function 
         //but without this key word not working, why?

        },

        getMyCar2: function(){ 
           return brand   " "   model   " "   color;  
           //NotWorking: return carBrand   carModel   carColor
        }
    };
}

let bmw = selectCar("bmw", "X6", "White"); console.log("My Car Model is: " bmw.getMyCar1());

let audi = selectCar("Audi", "A8", "Red"); console.log("My Car Model is: " audi.getMyCar2());

CodePudding user response:

It depends on what you want to achieve. i.e., If you want that function to return the current state of a car instance, you have getMycar1 function: Example:

let bmw = selectCar("bmw", "X6", "White"); 
bmw.carColor= "black"
console.log("My Car Model is: "   bmw.getMyCar2());

Result is:

My Car Model is: bmw X6 black

Here we changed car color and is reflected in the function.

on the other hand if you want a method to show initial state of car, getMyCar2 function is for you as it does change car attributes.

let audi = selectCar("Audi", "A8", "Red");
audi.carColor = 'black'
console.log("My Car Model is: "   audi.getMyCar2());

My Car Model is: Audi A8 Red

getMyCar2 function uses parameters passed to the function as values and so doesnt change its output when any attribute is changed in a car instance

  • Related