Constructors in JavaScript objects

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

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

19条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 10:38

    Maybe it's gotten a little simpler, but below is what I've come up with now in 2017:

    class obj {
      constructor(in_shape, in_color){
        this.shape = in_shape;
        this.color = in_color;
      }
    
      getInfo(){
        return this.shape + ' and ' + this.color;
      }
      setShape(in_shape){
        this.shape = in_shape;
      }
      setColor(in_color){
        this.color = in_color;
      }
    }
    

    In using the class above, I have the following:

    var newobj = new obj('square', 'blue');
    
    //Here, we expect to see 'square and blue'
    console.log(newobj.getInfo()); 
    
    newobj.setColor('white');
    newobj.setShape('sphere');
    
    //Since we've set new color and shape, we expect the following: 'sphere and white'
    console.log(newobj.getInfo());
    

    As you can see, the constructor takes in two parameters, and we set the object's properties. We also alter the object's color and shape by using the setter functions, and prove that its change remained upon calling getInfo() after these changes.

    A bit late, but I hope this helps. I've tested this with a mocha unit-testing, and it's working well.

提交回复
热议问题