Home > Article > Web Front-end > How to use constructors in JavaScript
This article will share knowledge about constructors in JavaScript and has certain reference value. I hope it will be helpful to everyone's learning.
The constructor is actually a regular function, but the first letter should be capitalized when naming, and when calling the constructor, be careful to instantiate it with the new keyword. Such use means that this is created empty at the beginning, and Return the filled space at the end, which will be introduced in detail in the article.
Constructor generation
this creates null at the beginning and returns the filled null at the end
function Student(name age){ this.name=name; this.age=age; } var student=new Student("张三","18"); var student1=new Student("李四","19");
When Student() is executing the function, the following steps will be performed:
(1) Create and allocate a new empty object this.
(2) Function body execution. Usually it will modify this, adding new properties to it.
(3)this return value.
Similarly, if we want to create more students, we can call new Student(), each time the method is simple and easy to read.
This is the main purpose of the constructor: to implement reusable object creation code.
Constructor return
Generally, constructors do not have a return statement, and their task is to write the required things into this. and generate results automatically.
But if there is a return, it will become very simple. For example, if return is called using object, it will return not this, that is, the return object returns the object, and this returns all other situations
For example, return overrides this by returning an object
function Student() { this.name = "张三"; return { name: "李四" }; //return 一个对象 } console.log( new Student().name );
Because an object is returned, the value in return is returned instead of the value in this
But if we return a null value, then what is returned is this value
<script> function Student() { this.name = "张三"; return; //return 一个空对象 } console.log(new Student().name ); </script>
Methods in the constructor
The constructor can not only add properties but also methods, making the constructor more flexible in creating objects
<script> function Student(name) { this.name = name; this.friend=function(){ console.log("this my friend:"+this.name); }; } var student=new Student("张三"); student.friend(); </script>
Summary: That’s it for this article That’s the entire content of the article. I hope it will be helpful for everyone to learn constructors.
The above is the detailed content of How to use constructors in JavaScript. For more information, please follow other related articles on the PHP Chinese website!