Home >Web Front-end >JS Tutorial >How to use constructor in js
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:
<code class="js">let obj = new Object(); console.log(obj.constructor); // 输出:Object</code>
<code>constructor</code> Can be used as a function to create new objects:
<code class="js">class Person { constructor(name) { this.name = name; } } let person = new Person("John"); console.log(person instanceof Person); // 输出:true</code>
##constructor Can be used to set the prototype of the object:
<code class="js">function Animal() {} function Dog() {} Dog.prototype = new Animal(); let dog = new Dog(); console.log(dog.constructor); // 输出:Dog</code>
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!