Getters \ setters for dummies

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

    Although often we are used to seeing objects with public properties without any access control, JavaScript allows us to accurately describe properties. In fact, we can use descriptors in order to control how a property can be accessed and which logic we can apply to it. Consider the following example:

    var employee = {
        first: "Boris",
        last: "Sergeev",
        get fullName() {
            return this.first + " " + this.last;
        },
        set fullName(value) {
            var parts = value.toString().split(" ");
            this.first = parts[0] || "";
            this.last = parts[1] || "";
        },
        email: "boris.sergeev@example.com"
    };
    

    The final result:

    console.log(employee.fullName); //Boris Sergeev
    employee.fullName = "Alex Makarenko";
    
    console.log(employee.first);//Alex
    console.log(employee.last);//Makarenko
    console.log(employee.fullName);//Alex Makarenko
    

提交回复
热议问题