Я читал главу 2 о методах Apres Javascript Pro и, в частности, раздел о Методы Provate .
В качестве примера показан следующий фрагмент кода:
// 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, которая приводит к неправильной настройке внутренних функций.
Действительно, создавая переменную , , указывающую на , , предыдущий код работает, как и ожидалось.
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();
}
Итак, мой вопрос:
- Всегда нужно создавать эту переменную?
Если да, это означает, что пример был совершенно неверным.