Constructors in JavaScript objects

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

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

19条回答
  •  半阙折子戏
    2020-11-22 10:39

    It seems to me most of you are giving example of getters and setters not a constructor, ie http://en.wikipedia.org/wiki/Constructor_(object-oriented_programming).

    lunched-dan was closer but the example didn't work in jsFiddle.

    This example creates a private constructor function that only runs during the creation of the object.

    var color = 'black';
    
    function Box()
    {
       // private property
       var color = '';
    
       // private constructor 
       var __construct = function() {
           alert("Object Created.");
           color = 'green';
       }()
    
       // getter
       this.getColor = function() {
           return color;
       }
    
       // setter
       this.setColor = function(data) {
           color = data;
       }
    
    }
    
    var b = new Box();
    
    alert(b.getColor()); // should be green
    
    b.setColor('orange');
    
    alert(b.getColor()); // should be orange
    
    alert(color); // should be black
    

    If you wanted to assign public properties then the constructor could be defined as such:

    var color = 'black';
    
    function Box()
    {
       // public property
       this.color = '';
    
       // private constructor 
       var __construct = function(that) {
           alert("Object Created.");
           that.color = 'green';
       }(this)
    
       // getter
       this.getColor = function() {
           return this.color;
       }
    
       // setter
       this.setColor = function(color) {
           this.color = color;
       }
    
    }
    
    var b = new Box();
    
    alert(b.getColor()); // should be green
    
    b.setColor('orange'); 
    
    alert(b.getColor()); // should be orange
    
    alert(color); // should be black
    

提交回复
热议问题