プログラミング学習ノート

プログラミング学習の記録用です。

クラス内のメソッドAの変数をメソッドBの引数で受け取る

実現したいこと

あるメソッドのデータを別のデータの引数で受け取りたい。

エラー

Uncaught SyntaxError: Identifier 'name' has already been declared

同じスコープ内で変数名が2回以上宣言されていることを示している。
JavaScriptでは、同じスコープ内で変数名を再宣言することはできない。

ソースコード

class Student {
  constructor(name) {
    let name = name;
  }
  hello (name) {
    return `こんにちは、${name}です。`
  }
}

let student = new Student('田中');
console.log(student.hello());

問題

ただletで変数に代入するだけでは、インスタンスの持ち物になっていない。
インスタンスのプロパティとするには、thisを使う必要がある。

試したこと

メソッドの引数をthis.nameとした。

class Student {
  constructor(name) {
    this.name = name;
  }
  hello (this.name) {
    return `こんにちは、${this.name}です。`
  }
}

let student = new Student('田中');
console.log(student.hello());

Uncaught SyntaxError: Unexpected token 'this'構文エラーとなった。

解決法

メソッドの定義の中でthis.songsを参照した。

class Student {
  constructor(name) {
    this.name = name;
  }
  hello () {
    return `こんにちは、${this.name}です。`
  }
}

let student = new Student('田中');
console.log(student.hello());

プロパティへのアクセス方法が間違っていた。
プロパティを参照するだけなら引数で受け渡しする必要はなかった。