ค่าของ this
ค่า this อ้างอิงถึงอ็อบเจ็กต์ปัจจุบัน
ค่านี้ถูกใช้อย่างกว้างขวางใน JavaScript
ตัวอย่างเช่นในฟังก์ชันและ OOP
ไวยากรณ์
this.อ็อบเจ็กต์ปัจจุบัน;
ตัวอย่าง
มาใช้ this เพื่อแสดง
ค่าของอินพุตที่เสียโฟกัส
ในคอนโซลกัน:
<input id="elem" value="text">
let input = document.querySelector('#elem');
input.addEventListener('blur', func);
function func() {
console.log(this.value);
}
ตัวอย่าง
มาใช้ this เพื่อแสดง
ค่าของอินพุตที่ไม่ได้อยู่
ในโฟกัสในคอนโซลกัน:
<input id="elem" value="text">
let input = document.querySelector('#elem');
input.addEventListener('blur', func);
function func() {
console.log(this.value);
}
ตัวอย่าง
คราวนี้มาดูการใช้งาน
this ใน OOP
ในคลาส Student เราจะเขียนฟังก์ชัน show
ซึ่งจะแสดงชื่อและนามสกุล
ของนักเรียนของเรา:
class Student {
name;
surn;
show() {
return this.name + ' ' + this.surn;
}
};
let stud = new Student;
stud.name = 'John';
stud.surn = 'Smit';
console.log(stud.show());