Tôi tìm thấy mã ví dụ này:Cách "này" hoạt động trong các hàm được gán trong hàm tạo?
function personFullName() {
return this.first + ' ' + this.last;
}
function Person(first, last) {
this.first = first;
this.last = last;
this.fullName = personFullName;
}
var dude = new Person("Michael", "Jackson");
alert(dude.fullName());
Cảnh báo nào "Michael Jackson". Tôi đã thay đổi nó để gọi personFullName
từ các nhà xây dựng thay vì gán đối tượng chức năng:
function personFullName() {
return this.first + ' ' + this.last;
}
function Person(first, last) {
this.first = first;
this.last = last;
this.fullName = personFullName();
}
var dude = new Person("Michael", "Jackson");
alert(dude.fullName);
tôi mong chờ các "FullName" bất động sản đến nay là một chuỗi thay vì một hàm. Nhưng bây giờ nó cảnh báo "undefined undefined". Bất cứ ai có thể giải thích lý do tại sao phiên bản của tôi không hoạt động?
Xem câu trả lời này để biết giải thích đầy đủ về cách thức hoạt động của 'this': http://stackoverflow.com/questions/13441307/how-does-the-this-keyword-in-javascript-act-within-an-object -literal/13441628 # 13441628 – slebetman