Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use object.assign this way? (new object onto empty function in module exports)

I recently saw this in some source code:

    module.exports = Object.assign(function GamepadButton() {}, {
            FACE_1: 0,
            FACE_2: 1,
            FACE_3: 2,
            FACE_4: 3,
         // etc...
        });

Why would one do this? Why assign an object to an empty newly declared function? What's going on here? (I assume the module.exports is irrelevant here, but just in case it isn't, I've included that as well.)

source: https://github.com/donmccurdy/aframe-extras/blob/4a05b159a9f5b79321acf002b85fee6cfcddc4d2/dist/aframe-extras.controls.js#L9

like image 543
Kyle Baker Avatar asked Jun 26 '20 07:06

Kyle Baker


2 Answers

I'm not sure if this was the purpose of the author to write it this way,

BUT:

This is a typical way of adding static variables to a JavaScript class.

After running the code above, you can run

var myExports = new module.exports()
var myOtherExports = new module.exports()

and you can access the same FACE_1, FACE_2, etc variables from all instances with

myExports.constructor.FACE_1
myOtherExports.constructor.FACE_1

and also with

module.exports.FACE_1

The variables share the same reference (static variable behavior).

like image 170
Cristian Sarghe Avatar answered Nov 16 '22 07:11

Cristian Sarghe


With this code above you can actually create static methods and properties.

Static methods / properties are accessible without instantiating the class, here an example:

let x = Object.assign(
  function test(arg) {
    this.arg = arg;
    this.normalFunc = function () {
      return "i am a normal func";
    };
  },
  {
    test: "work",
    staticFunc() {
      return "i am a static function";
    },
  }
);

console.log(x.test);
console.log(x.staticFunc());
//console.log(x.normalFunc()); // error: x.normalFunc is not a function
//console.log(x.arg); // undefined
let y = new x(5);
console.log(y.normalFunc());
console.log(y.arg);

As you can see, x.arg and x.normalFunc are returning undefined / error. Even if i set this.arg = "test" for example it will be undefined.

In other hand i can access test and staticFunc because the act like a static propertie / method and static methods / properties are accessible without instantiating the class.

After instantiating x i was able to access normalFunc() and arg

The ES6 code would look like this:

class x {
  constructor(arg) {
    this.arg = arg;
    this.normalFunc = function () {
      return "i am a normal func";
    };
  }

  static test = "work";
  static staticFunc() {
    return "i am a static function";
  }
}
like image 2
Ifaruki Avatar answered Nov 16 '22 09:11

Ifaruki