What is the argument for using ES6 getters and setters over getProperty/setProperty convention?

前端 未结 2 1881
天涯浪人
天涯浪人 2021-01-01 19:07
class Foo {
    getName = () => this.name;

    setName = (name) => this.name = name;
}

and

         


        
2条回答
  •  忘掉有多难
    2021-01-01 19:45

    There aren't any specific things you can't do with getMethod() and setMethod(), but it allows for different code styles. For instance you could, with a get foo and set foo, write:

    obj.foo++;
    

    which would call the getter then the setter. You could, of course, have the set function then validate that the value is within a specific range, for instance. The traditional code would look like:

    obj.setFoo(obj.getFoo() + 1);
    

    You cannot distinguish between a direct property access and method access.

    That's kinda the point. I'd argue that if something is really expensive, you just shouldn't use getters for it.

提交回复
热议问题