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

วิธีใช้ Boolean ใน JavaScript Constructors

ใช้เมธอด constructor() ของ Boolean คืน reference ไปยัง Boolean function ที่สร้าง instance's prototype

ตัวอย่าง

<html>
  <head>
    <title>JavaScript constructor() Method</title>
  </head>
  <body>
    <script>
      var bool = new Boolean();
      document.write("bool.constructor() is: " + bool.constructor);
    </script>
  </body>
</html>

ผลลัพธ์

bool.constructor() is: function Boolean() { [native code] }

Constructor Property ทั่วไป

ทุก object ใน JavaScript มี property constructor ชี้ไปยัง constructor function ที่สร้างมัน:

var str = "hello";
str.constructor === String;   // true

var num = 42;
num.constructor === Number;   // true

var arr = [];
arr.constructor === Array;    // true

var obj = {};
obj.constructor === Object;   // true

var bool = true;
bool.constructor === Boolean; // true

การใช้งานจริง

// ตรวจสอบชนิด object
function getType(obj) {
  return obj.constructor.name;
}

getType("hello");  // "String"
getType(42);       // "Number"
getType([]);       // "Array"
getType({});       // "Object"
getType(true);     // "Boolean"

// สร้าง instance ใหม่แบบ dynamic
var arr = [1,2,3];
var newArr = new arr.constructor(4,5,6); // [4,5,6]

หมายเหตุ: constructor property สามารถถูก overwrite ได้ ไม่ปลอดภัย 100% สำหรับ type checking