ใน JavaScript คีย์เวิร์ด this ใช้เป็น reference อ้างอิงถึง object หรือ subject ของโค้ดที่กำลัง execute
ตัวอย่าง
<script>
var college = {
subject: "Maths",
lecturer: "Amy",
details: function() {
document.write(this.subject);
}
}
</script>
กฎการกำหนดค่า this (this binding)
| บริบท (Context) | this ชี้ไปที่ |
|---|---|
| Global scope | global object (window ใน browser, global ใน Node.js) |
| Function (standalone, non-strict) | global object |
| Function (strict mode) | undefined |
| Method (obj.method()) | object ที่เรียก (obj) |
| Constructor (new Fn()) | instance ใหม่ที่สร้างขึ้น |
| Arrow function | lexical this (this ของ enclosing scope) |
| Event handler (inline) | element ที่ trigger event |
| Event handler (addEventListener) | element ที่ attach listener |
ตัวอย่างเพิ่มเติม
const user = {
name: "John",
greet() {
console.log(this.name); // "John" - method call
}
};
user.greet(); // "John" - this = user
const fn = user.greet;
fn(); // undefined (strict) / window (non-strict) - this lost
// Arrow function - lexical this
const obj = {
value: 42,
regular: function() { return this.value; },
arrow: () => this.value
};
obj.regular(); // 42
obj.arrow(); // undefined (this = global/window)