我在閱讀Apres Javascript Pro技術的第2章,特別是關於Provate方法的章節。Javascript私有方法
下面的代碼段被示出爲一個示例:
// 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行中,當創建新的課堂對象,
var class = new Classroom(["Jhon", "Bob"], "Mr. Smith");
以下錯誤被拋出:
Uncaught TypeError: Cannot call method 'join' of undefined.
閱讀douglas.crockford.com/private.html,我發現這個:
By convention, we make a private that variable. This is used to make the object available to the private methods. This is a workaround for an error in the ECMAScript Language Specification which causes this to be set incorrectly for inner functions.
確實創造了是變量指向這個,前面的代碼按預期方式工作。
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();
}
所以我的問題是:
- 它總是需要創建一個變量?
如果是的話,這意味着例子是明確錯誤的。
如果這些錯誤在第2章中,我不敢在後面的章節中看到代碼示例! – Matt