SoFunction
Updated on 2025-04-06

JavaScript constructors Essential knowledge for learning facial objects

Copy the codeThe code is as follows:

function A(x)
{
= x;
}
var obj = new A(5);
alert();

This code is very simple, but what we important is that we saw a very surprising result. Obj is given a property x by us, just like when we use an instance of a certain class in C#. So how did this attribute come about?

Key statement: =x. This sentence is to declare and assign attributes. Here, we will definitely ask, what is this? Why can I use it to declare and assign attributes?

In fact, this represents the obj we just instantiated, which is equivalent to using obj to call the properties, methods, etc. in constructor A.

So, how do we define a method in the constructor?

Copy the codeThe code is as follows:

function A(x,y)
{
= x;
= y;
= function(){alert(x)};
= function(){alert(y)};
}
var obj = new A(5,10);
alert();
alert();
();
();

The execution result is very simple. The results of 5, 10, 5, 10 pop up, you can see
Copy the codeThe code is as follows:

= function(){alert(x)};
= function(){alert(y)};

These two sentences of code define two methods, namely FunX and FunY. So, what if there is a situation now, what if we need to temporarily add a method to function A?

Copy the codeThe code is as follows:

function A(x,y)
{
= x;
= y;
}
= function(){alert("5")};
var obj = new A(5,10);
alert();
alert();
();
= function(){alert("10")};
();

Run this code and we can see that the pop-up result is the same as the previous one, but we defined both methods outside, and the method FunY is defined after instantiation. So what do you see here? Obviously, when we use the() statement, the code will reconstruct obj and then execute this method. So what if the code changes to this?
Copy the codeThe code is as follows:

();
= function(){alert("10")};

Obviously, FunY() will not execute the method.

Next time, I will talk about JavaScript's constructors and prototypes. If you have any questions or incorrect points, please feel free to make corrections and discuss them.