Constructors in JavaScript objects

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

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

19条回答
  •  -上瘾入骨i
    2020-11-22 10:32

    Using Nick's sample above, you can create a constructor for objects without parameters using a return statement as the last statement in your object definition. Return your constructor function as below and it will run the code in __construct each time you create the object:

    function Box()
    {
       var __construct = function() {
           alert("Object Created.");
           this.color = 'green';
       }
    
      this.color = '';
    
       this.getColor = function() {
           return this.color;
       }
    
       __construct();
    }
    
    var b = new Box();
    

提交回复
热议问题