PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, December 17, 2022

[FIXED] What is the correct syntax of JavaScript Factory Function? JavaScript Factory Function Syntax confusion

 December 17, 2022     factory, function, javascript, syntax     No comments   

Issue

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());


Solution

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



Answered By - Shresthdeep Gupta
Answer Checked By - David Goodson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing