Check source code of ApiValidator.js at github. I was taught to define a JS class using var apple = new function() {...
But this one starts with (function(){....
? Why is this?
Asked
Active
Viewed 53 times
-2

Dustin Sun
- 5,292
- 9
- 49
- 87
-
Neither `new function() { ...` nor `(function() { ...` are ways to define a class in JavaScript. – Pointy Sep 09 '15 at 20:43
-
Unless you are using ecmascript 6 there is no such thing as a class in javascript. What you are defining is functions. – bhspencer Sep 09 '15 at 20:46
2 Answers
1
First of all, var apple = new function() {}
is not a way of define a class.
and (function () {...})()
is a self-executing function that calling itself immediately.
For example: var fn = function () { // code };
so fn()
and (function() { // code })()
is similar.

thecodeparadox
- 86,271
- 21
- 138
- 164
0
The code in the GitHub starts with and ends with:
(function () {
//...
})();
This is called as a self-executing function or "Immediately-Invoked Function Expression" (IIFE). This encloses an anonymous function inside it and immediately executes it. And one more thing:
var apple = new function() {
}
The above is not a valid way of defining an object or a class.

Community
- 1
- 1

Praveen Kumar Purushothaman
- 164,888
- 24
- 203
- 252
-
2well `new function() { ... }` definitely will create an *object*, but I don't think too many people would say it creates a "class". – Pointy Sep 09 '15 at 20:46
-
That is NOT a closure. It's a self-executing function. A closure is only defined when something is being held on to that would have otherwise been garbage collected but can't because of a reference inside of some other function (a closure). – dmeglio Sep 09 '15 at 20:47
-
@Pointy Oops... Sorry about my mistake. How do I correct it? Should I remove it? – Praveen Kumar Purushothaman Sep 09 '15 at 20:47
-
-
1Technically it is called an "Immediately-Invoked Function Expression" (IIFE) http://stackoverflow.com/questions/8228281/what-is-the-function-construct-in-javascript – bhspencer Sep 09 '15 at 20:48
-
@Pointy Grr... What should the [edit] contain! `:P` – Praveen Kumar Purushothaman Sep 09 '15 at 20:48
-
2I wouldn't bother editing it. This question has been asked many times before and will almost certainly be closed. – bhspencer Sep 09 '15 at 20:49
-
-
@PraveenKumar well I guess you could say that it's a (somewhat unusual) way of instantiating an object. I guess it might be a useful way of building an object with a single expression when you can't use an object initializer for whatever reason. – Pointy Sep 09 '15 at 21:00