factory function code example

Example 1: factory function javascript

function createPerson(firstName, lastName) {
  return {
    firstName: this.firstName,
    lastName: this.lastName,
    getFullName: function () {
      return `${this.firstName} ${this.lastName}`
    }
  }
}

let user = createPerson('John', 'Doe');
console.log(user.getFullName()); // John Doe

Example 2: function(global factory)

// Standard UMD format
/*  |------------------|       |------------------|
    |                  v       v                  |
    |    (function (global, factory) {            |
    |                                             |
    |                                             |
    |        /* deleted for clarity */      /*    |*/
/*  |                 |---------------------------|
    |                 |
    |    }(this, function () { 'use strict';
    |       |
    |-------|
             /* So, global is window scope (which exports the function as a variable),
             and factory implements the module as a function.*/

/*       });*/