Create a JS class: IIFE vs return prototype
Asked Answered
E

1

19

Let's see two examples in which I'll try to explain what I want to understand.

var Car = function(){
  // Init class
  function Car() { };
  // Private func/vars
  var private = { color:'red' };
  // Public func/vars
  Car.prototype = {
    newColor: function(color) { private.color = color },
    getColor: function() { return private.color }
  };

  return Car.prototype; // return with prototype
};

var myCar = new Car();

And:

var Car = (function(){
  // Init class
  function Car() { };
  // Private func/vars
  var private = { color:'red' };
  // Public func/vars
  Car.prototype = {
    newColor: function(color) { private.color = color },
    getColor: function() { return private.color }
  };

  return Car; // avoid prototype adding parentheses on next line;
})();

var myCar = new Car();

Let's see!, Both class are created as function expression and both work equally. The only differences between them, are: The first return the Car function with its prototype property. The second works returning the Car function, avoiding the prototype property and instead use IIFE.

What's the differences between use return Car.prototype; and avoid IIFE and use return Car; using IIFE (parentheses at the end of the class declaration).

Ebner answered 5/11, 2012 at 4:45 Comment(3)
What exactly are you trying to achieve?Augustus
I'm trying to understand the theory of how it works in-depth, and what are the technical differences.Ebner
Do you intend to use the new operator with both of the Car objects returned ?Augustus
W
18

The second code sample is the proper way to achieve what you're looking for. You create an immediately-executing function, inside of which you create a new function, add to its prototype, and then return it.

The first example is a bit odd, and doesn't quite create a constructor function properly. The line

return Car.prototype; // return with prototype

causes your Car function to simply always return the object literal that you had previously assigned to Car.prototype. This overrides the normal behavior of a function invoked with new


Just one thing to note, this line:

Car.prototype = {
   newColor: function(color) { private.color = color },
   getColor: function() { return private.color }
};

will cause the constructor property of newly create objects to no longer point to your Car function. There are two easy ways to fix this if this is important to you.

Car.prototype = {
   newColor: function(color) { private.color = color },
   getColor: function() { return private.color }
};
Car.prototype.constructor = Car;   // <-------- add this line

Or change the above to

Car.prototype.newColor = function(color) { private.color = color };
Car.prototype.getColor = function() { return private.color };
Westlund answered 5/11, 2012 at 5:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.