Getters \ setters for dummies

后端 未结 12 2336
说谎
说谎 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:16

    Getters and setters really only make sense when you have private properties of classes. Since Javascript doesn't really have private class properties as you would normally think of from Object Oriented Languages, it can be hard to understand. Here is one example of a private counter object. The nice thing about this object is that the internal variable "count" cannot be accessed from outside the object.

    var counter = function() {
        var count = 0;
    
        this.inc = function() {
            count++;
        };
    
        this.getCount = function() {
            return count;
        };
    };
    
    var i = new Counter();
    i.inc();
    i.inc();
    // writes "2" to the document
    document.write( i.getCount());
    

    If you are still confused, take a look at Crockford's article on Private Members in Javascript.

提交回复
热议问题