Getters \ setters for dummies

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

    Sorry to resurrect an old question, but I thought I might contribute a couple of very basic examples and for-dummies explanations. None of the other answers posted thusfar illustrate syntax like the MDN guide's first example, which is about as basic as one can get.

    Getter:

    var settings = {
        firstname: 'John',
        lastname: 'Smith',
        get fullname() { return this.firstname + ' ' + this.lastname; }
    };
    
    console.log(settings.fullname);
    

    ... will log John Smith, of course. A getter behaves like a variable object property, but offers the flexibility of a function to calculate its returned value on the fly. It's basically a fancy way to create a function that doesn't require () when calling.

    Setter:

    var address = {
        set raw(what) {
            var loc = what.split(/\s*;\s*/),
            area = loc[1].split(/,?\s+(\w{2})\s+(?=\d{5})/);
    
            this.street = loc[0];
            this.city = area[0];
            this.state = area[1];
            this.zip = area[2];
        }
    };
    
    address.raw = '123 Lexington Ave; New York NY  10001';
    console.log(address.city);
    

    ... will log New York to the console. Like getters, setters are called with the same syntax as setting an object property's value, but are yet another fancy way to call a function without ().

    See this jsfiddle for a more thorough, perhaps more practical example. Passing values into the object's setter triggers the creation or population of other object items. Specifically, in the jsfiddle example, passing an array of numbers prompts the setter to calculate mean, median, mode, and range; then sets object properties for each result.

提交回复
热议问题