Getters \ setters for dummies

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

    In addition to @millimoose's answer, setters can also be used to update other values.

    function Name(first, last) {
        this.first = first;
        this.last = last;
    }
    
    Name.prototype = {
        get fullName() {
            return this.first + " " + this.last;
        },
    
        set fullName(name) {
            var names = name.split(" ");
            this.first = names[0];
            this.last = names[1];
        }
    };
    

    Now, you can set fullName, and first and last will be updated and vice versa.

    n = new Name('Claude', 'Monet')
    n.first # "Claude"
    n.last # "Monet"
    n.fullName # "Claude Monet"
    n.fullName = "Gustav Klimt"
    n.first # "Gustav"
    n.last # "Klimt"
    

提交回复
热议问题