In this article, we will check if the constructor of an object is a JavaScript object. The constructor property of any JavaScript variable returns a reference to theObjectconstructor that created the instance object. The value of this property is a reference to the function itself.
All objects have a constructor attribute, and objects created without a constructor will have a constructor attribute pointing to the base object constructor type.
To check if the constructor of the provided value is an object created by the object constructor, we need to compare the object's constructor property value with the corresponding object constructor reference. The constructor property returns a reference to the constructor that created the instance.
The following is the function syntax to check whether the constructor of an object is Object
function check(obj) { return obj.constructor === Object ? true : false }
In the following program, we check six Whether the object's constructor is a JavaScript object.
Check if Constructor is Object
Click on the check button all test cases
Test Case 1: {}
Constructor is Object:
Test Case 2: new Number(3)
Constructor is Object:
Test Case 3: new Object
Constructor is Object:
Test Case 4: new Object()
Constructor is Object:
Test Case 5: []
Constructor is Object:
Test Case 6: "Object Constructor"
Constructor is Object:
When the "Check" button is clicked, all the test cases will run and show the output as true or false. As we can see in the above code, if the object is created by the object constructor, the result will be reflected as true, otherwise it will be displayed as false. In the above code, test cases 1, 3, and 4 result in true because they are all created using the object constructor. Here, the object constructor property returns a value equal to the object in cases 1, 3, and 4.
In the following program, we find the constructors of four different objects created using different methods. We use theObject.constructorproperty to find the object's constructor.
Find the Constructor of Objects
The above is the detailed content of How to check if an object's constructor is a JavaScript object?. For more information, please follow other related articles on the PHP Chinese website!