Apres Javascript Pro テクニックの第 2 章、特にProvate Methodsに関するセクションを読んでいました。
例として、次のコード スニペットを示します。
// Listing 2-23. Example of a Private Method Only Usable by the Constructor Function
function Classroom(students, teacher) {
// A private method for displaying all the students in the class
function disp() {
alert(this.names.join(", ")); // i think here there is an error. Should be alert(this.students.join(", "));
}
// Store the class data as public object properties
this.students = students;
this.teacher = teacher;
disp();
}
4 行目のエラーは別として、新しい Classroom オブジェクトを作成すると、
var class = new Classroom(["Jhon", "Bob"], "Mr. Smith");
次のエラーがスローされます。
Uncaught TypeError: Cannot call method 'join' of undefined.
douglas.crockford.com/private.html を読んで、これを見つけました。
慣例により、その変数をプライベートにします。これは、オブジェクトをプライベート メソッドで使用できるようにするために使用されます。これは、ECMAScript 言語仕様のエラーの回避策であり、内部関数に対してこれが正しく設定されません。
実際、thisを指すthat変数を作成すると、前のコードは期待どおりに機能します。
function Classroom(students, teacher) {
var that;
// A private method used for displaying al the students in the class
function disp() {
alert(that.students.join(", "));
}
// Store the class data as public object properties
[...]
that = this;
disp();
}
だから私の質問は:
- その変数を作成することは常に必要ですか?
はいの場合、これは例が決定的に間違っていたことを意味します。