こんにちは、水田です。
JavaScriptのset構文についてです。JavaScriptのセッターは、オブジェクトのプロパティに値を設定する際にカスタムの処理を行えるメソッドで、setキーワードを使って定義します。セッターを使うと、プロパティへの値の設定時にデータの検証や変換ができ、設定されるデータに制約を加えることが可能です。たとえば、set fullName(name)のように定義し、person.fullName = “John Doe”と設定すると、セッターが呼び出されます。セッターは通常1つの引数を取り、オブジェクトの他のプロパティを操作して内部状態を更新します。セッターにより、外部からのプロパティへのアクセスを管理し、データの整合性を保ちながら柔軟にプロパティ値を設定できます。
class Person {constructor(firstName, lastName) {this.firstName = firstName;this.lastName = lastName;}get fullName() {return `${this.firstName} ${this.lastName}`;}set fullName(name) {const splits = name.split(" ");if (splits.length === 2) {this.firstName = splits[0];this.lastName = splits[1];} else {console.error('input error');}}} const person = new Person();console.log(person.fullName);// "undefined undefined" person.fullName = "John Doe"; console.log(person.fullName);// "John Doe"