使用javascript setters/getters

use*_*119 3 javascript ecmascript-6

所以我得到了我的Cube课程

class Cube{
    constructor(txt){
        this._text = txt;
    }
    get text(){
        return this._text;
    }
    set text(txt){
        this._text = txt;
    }
}
Run Code Online (Sandbox Code Playgroud)

我可以实现类似的东西

let temp = new Cube('hello');
Run Code Online (Sandbox Code Playgroud)

在这一点上,我不明白setter和getter的用法,因为我可以做到这两点:

temp.text = 'bye';
console.log(temp.text);//shows bye
console.log(temp._text);//shows bye
temp._text = 'hello again';
console.log(temp.text);//shows hello again
console.log(temp._text);//shows hello again
Run Code Online (Sandbox Code Playgroud)

所以当我想做类似的事情时,我假设我想要使用setter的唯一方法:

set text(txt){
    this._text += txt;
}
Run Code Online (Sandbox Code Playgroud)

有没有其他理由使用setter和getter?

T.J*_*der 6

在这一点上,我不明白setter和getter的用法因为我可以做到这两点:[使用text和使用_text]

只是因为您已将值存储在实例的属性中.您不必这样做,您可以将其存储在其他地方:

const Cube = function() {
  const privateData = new WeakMap();
  return class Cube {
    constructor(txt){
      privateData.set(this, {text: txt});
    }
    get text(){
      return privateData.get(this).text;
    }
    set text(txt){
      privateData.get(this).text = txt;
    }
  };
};

let temp = new Cube('hello');
temp.text = 'bye';
console.log(temp.text);  // shows bye
console.log(temp._text); // shows undefined
Run Code Online (Sandbox Code Playgroud)

或者只是让在课外使用更难(但并非不可能):

const Cube = function() {
  const textProp = Symbol();
  return class Cube {
    constructor(txt){
        this[textProp] = txt;
    }
    get text(){
        return this[textProp];
    }
    set text(txt){
        this[textProp] = txt;
    }
  };
};

let temp = new Cube('hello');
temp.text = 'bye';
console.log(temp.text);  // shows bye
console.log(temp._text); // shows undefined
Run Code Online (Sandbox Code Playgroud)

还要注意,由于getset只是功能,你可以做任何事情在其中.例如,可能set text会删除任何前导和尾随空格.也许有没有set text和它只有一个getter.也许设置text更新一些其他属性.也许它会记录更改,因此您可以对该更改提供"撤消".也许它会记录调试版本中的调试更改.

选择是无止境的.关键是,通过为您提供一种挂钩属性获取/设置操作的方法,您可以对它们执行任何操作.(当然你可以使用和滥用...... :-))

在评论中你问过:

所以在我的情况下(第一个代码片段),基本上不需要get/set(因为我不想修改我的输入和输出)?

如果你只想要一个普通的,无聊的属性(这是我们大多数时候最想要的),就不需要getter/setter,只需使用普通属性:

class Cube {
    constructor(txt) {
        this.text = txt;
    }
}
Run Code Online (Sandbox Code Playgroud)

最棒的是,如果你后来意识到你需要一个getter/setter,你可以改变它,而使用的代码Cube仍然有效.:-)