What are getters and setters for in ECMAScript 6 classes?

前端 未结 4 2016
太阳男子
太阳男子 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:04

    class Employee {
    
        constructor(name) {
          this._name = name;
        }
    
        doWork() {
          return `${this._name} is working`;
        }
    
        get name() {
          // when you get this by employeeInstance.mame
          // the code below will be triggered
          // and you can do some logic here
          // just like `console.log` something you want
          console.log('get triggered!')
          return this._name.toUpperCase();
        }
    
        set name(newName) {
          // the same as `get`
          // when you employeeInstance.mame = 'xxx'
          // the code blew will be trigged
          // and you can also do some logic 
          // like here is a `console.log` and `if check`
          console.log('set triggered!')
          if (newName) {
            this._name = newName;
          }
        }
      }
    
      const employeeInstance = new Employee('mike')
      employeeInstance.name
      employeeInstance.name = '' // this won't be success, because the `if check`
      console.log(employeeInstance.name)
    
      // => 
      // get triggered
      // set triggered
      // get triggered
      // MIKE
    

    Anyway the getter and setter is just like a spy. It spies the property of an object, so that you can do something, every time you get or set the value of the property.

提交回复
热议问题