Trong JS, method thực chất là property có giá trị là function. Khi gọi obj.method(), từ khóa this bên trong function trỏ đến obj.
Cú pháp
const obj = {
property: 'value',
methodName: function() {
// this trỏ đến obj
return this.property;
}
};
Ví dụ 1: Full name từ firstName + lastName
<script>
const employee = {
firstName: 'Raju',
lastName: 'Nayak',
designation: 'Engineer',
fullName: function() {
return this.firstName + ' ' + this.lastName;
}
};
document.write(employee.fullName()); // "Raju Nayak"
</script>
Ví dụ 2: Method trả về chuỗi mô tả
<script>
const student = {
name: 'Susan',
country: 'USA',
rollNo: '5',
details: function() {
return `The student named ${this.name} is allocated with rollno ${this.rollNo}`;
}
};
document.write(student.details());
// "The student named Susan is allocated with rollno 5"
</script>
Lưu ý quan trọng về this
Giá trị this phụ thuộc vào cách gọi, không phải nơi định nghĩa:
const obj = {
name: 'JS',
getName: function() { return this.name; }
};
obj.getName(); // 'JS' — this = obj
const fn = obj.getName;
fn(); // undefined (strict mode) hoặc window (non-strict) — this mất biding
// Fix: bind
const boundFn = obj.getName.bind(obj);
boundFn(); // 'JS'
Arrow function trong object
Không dùng arrow function cho method nếu cần this — arrow function không có this riêng, kế thừa từ scope cha.
const obj = {
name: 'JS',
// Sai:
getName: () => this.name, // this = window/global
// Đúng:
getName() { return this.name; }
};
ES6 Method Shorthand
const obj = {
name: 'JS',
getName() { // Rút gọn từ getName: function()
return this.name;
}
};