Getters \ setters for dummies

后端 未结 12 2160
说谎
说谎 2020-11-22 04:55

I\'ve been trying to get my head around getters and setters and its not sinking in. I\'ve read JavaScript Getters and Setters and Defining Getters and Setters and just not g

12条回答
  •  灰色年华
    2020-11-22 05:29

    You'd use them for instance to implement computed properties.

    For example:

    function Circle(radius) {
        this.radius = radius;
    }
    
    Object.defineProperty(Circle.prototype, 'circumference', {
        get: function() { return 2*Math.PI*this.radius; }
    });
    
    Object.defineProperty(Circle.prototype, 'area', {
        get: function() { return Math.PI*this.radius*this.radius; }
    });
    
    c = new Circle(10);
    console.log(c.area); // Should output 314.159
    console.log(c.circumference); // Should output 62.832
    

    (CodePen)

提交回复
热议问题