ค่าของ this

ค่า this อ้างอิงถึงอ็อบเจ็กต์ปัจจุบัน ค่านี้ถูกใช้อย่างกว้างขวางใน JavaScript ตัวอย่างเช่นในฟังก์ชันและ OOP

ไวยากรณ์

javascriptthis.อ็อบเจ็กต์ปัจจุบัน;

ตัวอย่าง

มาใช้ this เพื่อแสดง ค่าของอินพุตที่เสียโฟกัส ในคอนโซลกัน:

html<input id="elem" value="text">
javascriptlet input = document.querySelector('#elem');
input.addEventListener('blur', func);

function func() {
  console.log(this.value);
}

ตัวอย่าง

มาใช้ this เพื่อแสดง ค่าของอินพุตที่ไม่ได้อยู่ ในโฟกัสในคอนโซลกัน:

html<input id="elem" value="text">
javascriptlet input = document.querySelector('#elem');
input.addEventListener('blur', func);

function func() {
  console.log(this.value);
}

ตัวอย่าง

คราวนี้มาดูการใช้งาน this ใน OOP ในคลาส Student เราจะเขียนฟังก์ชัน show ซึ่งจะแสดงชื่อและนามสกุล ของนักเรียนของเรา:

javascriptclass Student {
  name;
  surn;
  
  show() {
    return this.name + ' ' + this.surn;
  }
};
  
let stud = new Student;
stud.name = 'John';
stud.surn = 'Smit';
console.log(stud.show());

ดูเพิ่มเติม

  • เมธอด bind,
    ซึ่งผูก context เข้ากับฟังก์ชัน
  • เมธอด call,
    ซึ่งเรียกฟังก์ชันพร้อม context
  • เมธอด apply,
    ซึ่งเรียกฟังก์ชันพร้อม context