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

พรอเพอร์ตี้ของ Boolean Object ใน JavaScript

Boolean object แทนค่า 2 ค่า: "true" หรือ "false" หากค่า parameter ถูกละหรือเป็น 0, -0, null, false, NaN, undefined, หรือ "" object จะมีค่าเริ่มต้นเป็น false

Properties ของ Boolean Object

#Propertyคำอธิบาย
1constructorคืน reference ไปยัง Boolean function ที่สร้าง object
2prototypeอนุญาตให้เพิ่ม properties/methods ให้ object ทุกตัวที่สร้างจาก constructor นั้น

ตัวอย่าง: ใช้ prototype เพิ่ม property

<html>
  <head>
    <title>JavaScript Boolean object</title>
    <script>
      function book(title, author) {
        this.title = title;
        this.author = author;
      }
    </script>
  </head>
  <body>
    <script>
      var myBook = new book("WordPress Development", "Amit");
      book.prototype.price = null; // เพิ่ม property ให้ทุก book
      myBook.price = 500;
      document.write("Book title: " + myBook.title + "<br>");
      document.write("Book author: " + myBook.author + "<br>");
      document.write("Book price: " + myBook.price + "<br>");
    </script>
  </body>
</html>

คำอธิบาย

  • constructor: myBook.constructor === book → true
  • prototype: ใช้ขยาย functionality ให้ทุก instance (inheritance pattern แบบเก่า)

ใน ES6+ ใช้ Class แทน

class Book {
  constructor(title, author) {
    this.title = title;
    this.author = author;
    this.price = null;
  }
}
const myBook = new Book("WordPress Development", "Amit");
myBook.price = 500;