0

I didn't know you could create a function using new Object:

var myFunc = new Object(function myFunc () {})

Looking at the console, it seems identical to:

function myFunc () {}

Is there a reason to use new Object to create a function?

31piy
  • 23,323
  • 6
  • 47
  • 67
SRCP
  • 224
  • 2
  • 10

1 Answers1

1

According to the Object(...) documentation:

The Object constructor creates an object wrapper for the given value. If the value is null or undefined, it will create and return an empty object, otherwise, it will return an object of a Type that corresponds to the given value. If the value is an object already, it will return the value.

Functions are objects, therefore it will just return the function. The new Object(...) part is a no-op. So the code is basically just:

  var myFunc = function myFunc() { }

and that is barely equal to a function declaration

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • Thank you. I created that code from reading that documentation. Can't believe I missed that line. It is pretty late. To rephrase my other question, other than how they are defined, are functions created via function expressions identical to those created via function declarations? That's what I meant. – SRCP May 09 '19 at 10:58
  • I did see the link. I already know the difference in how they are defined as the code runs. I know about hoisting. Other than that, is everything else identical? – SRCP May 09 '19 at 17:49