Search code examples
javascriptclassprototypeiife

Create a JS class: IIFE vs return prototype


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).


Solution

  • 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 };