我正在阅读 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的变量,前面的代码按预期工作。
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();
}
所以我的问题是:
- 总是需要创建一个那个变量?
如果是,这意味着该示例绝对是错误的。