Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Cách dùng hàm JavaScript như một Object

Trong JS, hàm là first-class object. Có thể dùng Constructor Function để tạo đối tượng.

Ví dụ

<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: " + myBook.title + "<br>");
      document.write("Book author: " + myBook.author + "<br>");
    </script>
  </body>
</html>