How to use JavaScript constructor?
The constructor is to initialize an instance object, and the prototype attribute of the object is to inherit an instance object. This article will share with you a detailed explanation of the JavaScript constructor. Friends who are interested in knowledge about the JS constructor should learn together.
The constructor is to initialize an instance object, and the prototype attribute of the object is to inherit an instance object.
Notes on the constructor:
1. The first letter of the default function is capitalized
2. The constructor does not return anything. The new operator automatically creates the given types and returns them. When the constructor is called, new automatically creates the this object, and the type is the constructor type.
3. You can also call return explicitly in the constructor. If the returned value is an object, it will be returned instead of the newly created object instance. If the returned value is a primitive type, it is ignored and a newly created instance is returned.
function Person( name){ this.name =name; } var p1=new Person('John');
is equivalent to:
function person(name ){ Object obj =new Object(); obj.name =name; return obj; } var p1= person("John");
4. Because the constructor is also a function, it can be called directly, but Its return value is undefine. At this time, the this object in the constructor is equal to the global this object. this.name actually creates a global variable name. In strict mode, an error occurs when you call the Person constructor via new.
5. You can also use the Object.defineProperty() method in the constructor to help us initialize:
function Person( name){ Object.defineProperty(this, "name"{ get :function(){ return name; }, set:function (newName){ name =newName; }, enumerable :true, //可枚举,默认为false configurable:true //可配置 }); } var p1=new Person('John');
6. Use the prototype object in the constructor
//比直接在构造函数中写的效率要高的多 Person.prototype.sayName= function(){ console.log(this.name); };
But if there are many methods, most people will adopt a simpler method: directly use an object literal form Replace the prototype object as follows:
Person.prototype ={ sayName :function(){ console.log(this.name); }, toString :function(){ return "[Person "+ this.name+"]" ; } };
This method is very popular because you don’t have to type Person.prototype multiple times, but there is a side effect you must pay attention to:
The prototype object is rewritten in literal form and the properties of the constructor are changed, so it points to Object instead of Person. This is because the prototype object has a constructor property, which other object instances do not have. When a function is created, its prototype property is also created, and the constructor property of the prototype object points to the function. When the prototype object is rewritten using object literal form, its constructor property will be set to the generic object Object. In order to avoid this, you need to manually reset the constructor when rewriting the prototype object, as follows:
Person.prototype ={ constructor :Person, sayName :function(){ console.log(this.name); }, toString :function(){ return "[Person "+ this.name+"]" ; } };
Test again:
p1.constructor===Person
true
p1.constructor= ==Object
false
p1 instanceof Person
true
The above is the detailed content of How to use JavaScript constructor?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



In Python, every class has a constructor, which is a special method specified inside the class. The constructor/initializer will be called automatically when a new object is created for the class. When an object is initialized, the constructor assigns values to data members in the class. There is no need to define the constructor explicitly. But in order to create a constructor, we need to follow the following rules - For a class, it is allowed to have only one constructor. The constructor name must be __init__. Constructors must be defined using instance properties (just specify the self keyword as the first argument). It cannot return any value except None. Syntax classA():def__init__(self):pass Example Consider the following example and

C++ is a widely used object-oriented programming language. When defining the constructor of a class in C++, if you want to place the definition of the constructor outside the class, you need to add the class name as a qualifier to the definition of the constructor. To specify which class this constructor belongs to. This is a basic rule of C++ syntax. If this rule is not followed when defining the constructor of a class, a compilation error will appear, prompting "Constructors defined outside the class must be qualified with the class name." So, if you encounter this kind of compilation error, you should

Go language does not have constructors. Go language, as a structured language, does not have constructors in object-oriented languages. However, similar effects of constructors in object-oriented languages can be achieved in some ways, that is, using the process of structure initialization to simulate the implementation of constructors.

As the basis of prototypes and prototype chains, first understanding the constructor and its execution process can better help us learn the knowledge of prototypes and prototype chains. This article will take you to learn more about the constructor in JavaScript and introduce how to use the constructor to create a js object. I hope it will be helpful to you!

In C++ programming, the constructor is an important function used to initialize the member variables of a class. It is automatically called when an object is created to ensure proper initialization of the object. The constructor must be declared in the class, but sometimes you will encounter the error message "The constructor must be declared in the public area." This error is usually caused by incorrect access modifiers on the constructor. In C++, class member variables and member functions have an access modifier, including public, private, and protected.

In C++ programming, you may encounter the following error message: Constructors with only a single parameter must be declared explicit. This error message may confuse beginners. Next, let's take a look at what explicit is in C++, the reasons why this error message appears, and how to solve this problem. The role of explicit in C++, if we define a constructor that only receives one parameter, then we need to use the keyword explici

C++ is a powerful programming language, but it is inevitable to encounter various problems during use. Among them, the same constructor signature appearing multiple times is a common syntax error. This article explains the causes and solutions to this error. 1. Cause of the error In C++, the constructor is used to initialize the data members of the object when creating the object. However, if the same constructor signature is defined in the same class (that is, the parameter types and order are the same), the compiler cannot determine which constructor to call, causing a compilation error. For example,

How to create objects using the Object() function? The following article will introduce you to the method of creating objects using the Object() constructor (with three other methods of creating objects). I hope it will be helpful to you!
