在本文中,我們將檢查對象的構造函數是否是 JavaScript 對象。任何 JavaScript 變量的 constructor 屬性都會返回對創建實例對象的 Object 構造函數的引用。此屬性的值是對函數本身的引用。
所有對象都具有構造函數屬性,并且在沒有構造函數的情況下創建的對象將具有指向該基本對象構造函數類型的構造函數屬性。
要檢查提供的值的構造函數是否是由對象構造函數創建的對象,我們需要將對象的構造函數屬性值與相應的對象構造函數引用進行比較。 constructor 屬性返回對創建實例的構造函數的引用。
語法
以下是檢查對象的構造函數是否為 Object 的函數語法
function check(obj) {
return obj.constructor === Object ? true : false
}
登錄后復制
示例
在下面的程序中,我們檢查六個對象的構造函數是否為 JavaScript 對象。
<html>
<body>
<h3 >Check if Constructor is Object</h3>
<p> Click on the check button all test cases </p>
<p>Test Case 1: {} </p>
<p>Constructor is Object:
<span id="testcase1"> </span> </p>
<p>Test Case 2: new Number(3)</p>
<p>Constructor is Object:
<span id="testcase2"> </span> </p>
<p>Test Case 3: new Object </p>
<p>Constructor is Object:
<span id="testcase3"> </span> </p>
<p>Test Case 4: new Object() </p>
<p>Constructor is Object:
<span id="testcase4"> </span> </p>
<p> Test Case 5: [] </p>
<p>Constructor is Object:
<span id="testcase5"> </span> </p>
<p>Test Case 6: "Object Constructor" </p>
<p>Constructor is Object:
<span id="testcase6"> </span> </p>
<button onclick="runTestCases()"> Check </button>
<script>
// This function will check if created by Object constructor
function check(obj) {
return obj.constructor === Object ? true : false
}
function runTestCases() {
document.getElementById("testcase1").textContent =
check({});
document.getElementById("testcase2").textContent =
check(new Number(3));
document.getElementById("testcase3").textContent =
check(new Object);
document.getElementById("testcase4").textContent =
check(new Object());
document.getElementById("testcase5").textContent =
check([]);
document.getElementById("testcase6").textContent =
check("Object Conctructor");
}
</script>
</body>
</html>
登錄后復制
單擊“檢查”按鈕時,所有測試用例都將運行并顯示輸出為 true 或 false。正如我們在上面的代碼中看到的,如果對象是由對象構造函數創建的,則結果將反映為 true,否則將顯示結果為 false。在上面的代碼中,測試用例 1、3 和 4 的結果為 true,因為它們都是使用對象構造函數創建的。這里,對象構造函數屬性返回的值等于第 1、3 和 4 種情況下的對象。
示例(查找對象的構造函數)
在下面的程序中,我們發現使用不同方法創建的四個不同對象的構造函數。我們應用Object.constructor屬性來查找對象的構造函數。
<html>
<body>
<h3> Find the Constructor of Objects</h3>
<p id="demo"></p>
<script>
function Student(first, last, course) {
this.firstName = first;
this.lastName = last;
this.course = course;
}
const stud1 = new Student("John", "Doe", "M.Tech");
const stud2 = new Object();
const stud3 = new Object;
var stud4 = {
firstName: "John",
lastName: "Doe",
course: "M.Tech"
}
document.getElementById("demo").innerHTML +=`Constructor of stud1: ${stud1.constructor} <br>`;
document.getElementById("demo").innerHTML +=`<br>Constructor of stud2: ${stud2.constructor} <br>`;
document.getElementById("demo").innerHTML +=`<br>Constructor of stud3: ${stud3.constructor} <br>`;
document.getElementById("demo").innerHTML +=`<br>Constructor of stud4: ${stud4.constructor} <br>`;
</script>
</body>
</html>
登錄后復制
以上就是如何檢查對象的構造函數是否是 JavaScript 對象?的詳細內容,更多請關注www.92cms.cn其它相關文章!






