JavaScript Factory FunctionThe Factory Function is related to the constructor function or class functions. However, it produces and returns an object without requiring a new one. Factory Functions in JavaScript are identical to constructorfunctions. However, they don't require the 'this' keyword for inner values or the 'new' keyword when initialising new objects. Factory Functions can have inner values, arguments, etc., like regular functions. Unlike normal functions, factory functions return an object with any value, method, etc... If we need to produce several objects that contain the same logic, we may write the logic in a function and utilise it as a factory. It's like an actual factory making items. SyntaxThe following factory syntax is used to return multiple data using a function.
ExamplesThe following examples help to know about factory function and how to operate it using javascript. Example1The following factory function example is used to display multiple data using the function. The data is shown in the console using the console.log function. Output: The image shows multiple data using a single function. Example2The following factory function example is used to display mathematical operation and its output. Output: The image shows multiple data using a single function. Example3The following factory function example is used to display multiple data using the function. The data is shown in the console using the console.log function. Here, we use "var" to create variable. Output The image shows multiple data using a single function. Example4The following factory function example is used to display multiple data using the function. The data is shown in the console using the console.log function. Here we can use the fullname with a different object in the factory function. Output The image shows multiple data using a single function. Example5The following factory function example is used to display multiple nested function operations using the function. Here we can create two methods, division and multiplication, inside of the factory function. We can place a single value for all functions then javascript operates both multiplication and division for the single factory functions value. Output The image shows multiple data using a single function. ConclusionThe factory function in JavaScript is used to display multiple values using a single function. It is used to display data as per requirement.
Next TopicJavaScript for...in Loop
|