Create a JS class: IIFE vs return prototype

后端 未结 1 928
-上瘾入骨i
-上瘾入骨i 2020-12-14 08:40

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 fun         


        
相关标签:
1条回答
  • 2020-12-14 09:38

    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 };
    
    0 讨论(0)
提交回复
热议问题