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

วิธีใช้ JavaScript Function เป็น Object

ใน JavaScript Functions เป็น Objects (First-class Citizens) สามารถใช้เป็น Constructor สร้าง Object Instance ได้ (Constructor Pattern)

ตัวอย่าง: Constructor Function

<html>
  <head>
    <title>User-defined objects</title>
    <script>
      function Book(title, author) {
        this.title = title;
        this.author = author;
      }
    </script>
  </head>
  <body>
    <script>
      var myBook = new Book("Amit", "Python");
      document.write("Book title is: " + myBook.title + "<br>");
      document.write("Book author is: " + myBook.author + "<br>");
    </script>
  </body>
</html>

คำอธิบาย

  1. function Book(...) - Constructor Function (ขึ้นต้นด้วยตัวใหญ่เป็น Convention)
  2. this.title = title - กำหนด Property ให้ Instance
  3. new Book(...) - สร้าง Instance ใหม่ this ชี้ไปที่ Instance ใหม่นั้น
  4. myBook.title - เข้าถึง Property ของ Instance

เพิ่ม Method ให้ Prototype (ประหยัด Memory)

Book.prototype.getInfo = function() {
  return this.title + " by " + this.author;
};

var book1 = new Book("Book A", "Author 1");
var book2 = new Book("Book B", "Author 2");
book1.getInfo(); // "Book A by Author 1"
// getInfo แชร์กันทุก Instance (อยู่ใน Prototype)

Class Syntax (ES6) - Syntactic Sugar

class Book {
  constructor(title, author) {
    this.title = title;
    this.author = author;
  }

  getInfo() {
    return `${this.title} by ${this.author}`;
  }
}

const book = new Book("JS Guide", "Author");
book.getInfo();

Function Properties (เพราะเป็น Object)

function greet(name) { return "Hi " + name; }

greet.language = "th";     // เพิ่ม Property
greet.sayHi = () => "Hi";  // เพิ่ม Method

console.log(greet.name);      // "greet"
console.log(greet.length);    // 1 (parameter count)
console.log(greet.toString()); // Source code

สรุป: ใช้ new FunctionName() เพื่อสร้าง Object จาก Function (Constructor Pattern) ES6 ใช้ class แทน