Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

คีย์เวิร์ด "get" ก่อนฟังก์ชันใน Class - JavaScript

get ใช้สร้าง getter คล้าย C#, Java เรียกใช้เหมือน property ไม่ต้องใส่ ()

ตัวอย่างโค้ด

class Employee {
  constructor(name) {
    this.name = name;
  }
  get fullName() {
    return this.name;
  }
}

var employeeObject = new Employee("David Miller");
console.log(employeeObject.fullName);

รันด้วยคำสั่ง:

node fileName.js

ชื่อไฟล์: demo299.js

ผลลัพธ์

PS C:\Users\Amit\javascript-code> node demo299.js
David Miller

คำอธิบาย: get fullName() กำหนด getter เรียกด้วย employeeObject.fullName (ไม่ใช่ fullName()) มักคู่กับ set สำหรับ setter สร้าง computed property หรือ validation