What are getters and setters for in ECMAScript 6 classes?

前端 未结 4 2015
太阳男子
太阳男子 2020-11-29 17:44

I am confused as to what the point of getters and setters are in ECMAScript 6 classes. What is the purpose? Below is an example I am referring to:

class Empl         


        
4条回答
  •  情话喂你
    2020-11-29 18:25

    Getters and setters in ES6 serve the same purpose that they do in other languages... including ES5. ES5 already allows getters and setters via Object.defineProperty, though they're less clean and more cumbersome to use.

    Effectively, getters and setters allow you to use standard property access notation for reads and writes while still having the ability to customize how the property is retrieved and mutated without needed explicit getter and setter methods.

    In the Employee class above, this would mean you could access the name property like this:

    console.log(someEmployee.name);
    

    It would look like a normal property access, but it would actually call toUpperCase on the name before returning it. Similarly, doing this:

    someEmployee.name = null;
    

    would access the setter, and it would not modify the internal _name property because of the guard clause introduced in name's setter.

    See also the general question Why use getters and setters? for more information about why being able to modify the functionality of member access is useful.

提交回复
热议问题