ゲッターとセッターは、基本的プロパティオブジェクトのためGET-及びセット - アクションを捕捉するためにフックされています。それらは関数ですが、(このオブジェクトを使用するコードに)と表示されますは、プロパティのようです。
var mail = new Mail("@mail.com", Date.now(), "Testing", "Text");
console.log(mail.sender); //no brackets
セッターを追加すると、main.sender = "@foo.bar"
が追加されます。
そして、自分のゲッターが呼び出されて以来、あなたのコードが無限回帰で詰まっていないのではないかと思います。
class Mail {
constructor(sender, date, subject, text) {
this._sender = sender;
this._date = date;
this._subject = subject;
this._text = text;
}
//this IS `this.sender`!
//it should not `return this.sender`, since this would call this getter again,
//and you get stuck in an infinite recursion.
get sender() {
return this._sender;
}
//and a possible setter, that handles
//instance.sender = whatever;
set sender(value) {
this._sender = value;
}
}
編集:は
が、これは私が直接オブジェクトのフィールドにアクセスすることができますので、私はちょうどgetおよびsetメソッドを無視することができることを意味するのでしょうか?
JSでプロパティをパブリックにする必要はありません。このプロパティを定義するだけで、パブリックが利用できるようになります。 JSは別の方法で動作します。物事を非公開にするためにさらに努力する必要があります(締め切りを参照)。 JSでは、すべてがデフォルトで公開されています。
しかし、あなたは次のように、追加のタスクを満たすためにゲッター(およびセッター)を使用することができます。
class Person{
constructor(firstName, lastName){
//regular public properties
this.firstName = firstName;
this.lastName = lastName;
}
//a composed value, that you can access like a property
get fullName(){
return this.firstName + " " + this.lastName;
}
//you could also add a setter like this
set fullName(value){
[this.firstName, this.lastName] = value.split(/\s+/g);
}
}
var john = new Person("John", "Doe");
console.log(john.fullName);
ゲッターとセッターを使用するには、あなただけのプロパティを使用して設定する必要があります。 'mail.sender' – nicovank
@nicovank私は必要なメールプロパティに直接アクセスできますか?どのようなカプセル化の問題など、Javaでそうではありませんか? –
'mail.sender'を現在の状態で実行すると、無限再帰が発生します。 –