実現したいこと
あるメソッドのデータを別のデータの引数で受け取りたい。
エラー
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());
プロパティへのアクセス方法が間違っていた。
プロパティを参照するだけなら引数で受け渡しする必要はなかった。