-2

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?

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 Answers2

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