Constructors in JavaScript objects

后端 未结 19 2143
夕颜
夕颜 2020-11-22 10:21

Can JavaScript classes/objects have constructors? How are they created?

19条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 10:50

    Using prototypes:

    function Box(color) // Constructor
    {
        this.color = color;
    }
    
    Box.prototype.getColor = function()
    {
        return this.color;
    };
    

    Hiding "color" (somewhat resembles a private member variable):

    function Box(col)
    {
       var color = col;
    
       this.getColor = function()
       {
           return color;
       };
    }
    

    Usage:

    var blueBox = new Box("blue");
    alert(blueBox.getColor()); // will alert blue
    
    var greenBox = new Box("green");
    alert(greenBox.getColor()); // will alert green
    

提交回复
热议问题