Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Why does js need to use constructors

2025-03-11 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

Xiaobian to share with you why js needs to use the constructor, I hope you have something to gain after reading this article, let's discuss it together!

Using constructors to construct reusable objects

Functions in JS can be constructors or called as ordinary functions. When new is used to create an object, the corresponding function is a constructor, and when called through an object, it is an ordinary function.

Constructor is the function you construct. It is a special method. It is qualitatively different from ordinary functions. Its function is mainly used to initialize objects when creating objects, that is, to assign initial values to object members. The main characteristics of constructor are method name, initial capitalization, and use new.

If your object has many instances, or involves inheritance or constructor arguments, pay attention to the code comments

//creates a constructor function Person(name,address){ this.name = name; this.address = address;}//Add a method sayHelloPerson.prototype.sayHello = function(){ console.log('Hi I am ' + this.name);}//instantiate a p1 with constructor Person and pass var p1 = new Person ('postbird',' earth');//instantiate a p2 with constructor Person and pass var p2 = new Person ('ptbird','month');console.log(p1);//{name: "postbird", address: "earth"}console.log(p2);//{name: "ptbird", address: "month"}// p1 and p2 inherit Person's sayHello method p1.sayHello()//Hi I am ptbirdp2.sayHello()//Hi I am postbird

Patience taste above the code, such scalability will be better, you can create N instances, code reuse

After reading this article, I believe you have a certain understanding of "why js needs to use constructor". If you want to know more about it, welcome to pay attention to the industry information channel. Thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report