In JavaScript <code>constructor</code> Usage
<code>constructor</code> is a built-in property in JavaScript that points to the function that creates the object. It is used to initialize the state of an object when it is created.
Syntax:
<code>constructor</code>
Usage:
<code>constructor</code> Can be used for the following purposes:
let obj = new Object(); console.log(obj.constructor); // 输出:Object
<code>constructor</code> Can be used as a function to create new objects:
class Person { constructor(name) { this.name = name; } } let person = new Person("John"); console.log(person instanceof Person); // 输出:true
##constructor Can be used to set the prototype of the object:
function Animal() {} function Dog() {} Dog.prototype = new Animal(); let dog = new Dog(); console.log(dog.constructor); // 输出:Dog
Note:
is a read-only property and cannot be Revise.
properties point to the
Object function.
method, which is used to initialize instances of the class.
The above is the detailed content of How to use constructor in js. For more information, please follow other related articles on the PHP Chinese website!