CopyCode The Code is as follows: function a (x)
{
This. x = X;
}
VaR OBJ = new A (5 );
Alert (obj. X );
This code is very simple, but what is important is that we have seen a very surprised result. obj is assigned a property X, just like when we use an instance of a class in C. How is this property generated?
Key statement: This. x = x. This is an attribute declaration and assignment. Here, we will certainly ask, what is this? Why can I use this. X to declare and assign values to attributes?
In fact, this represents the just-instantiated OBJ, which is equivalent to calling the properties and methods in constructor A using obj.
So how do we define a method in the constructor?
Copy code The Code is as follows: function A (x, y)
{
This. x = X;
This. Y = y;
A. Prototype. FunX = function () {alert (x )};
A. Prototype. funy = function () {alert (y )};
}
VaR OBJ = new A (5, 10 );
Alert (obj. X );
Alert (obj. y );
OBJ. FunX ();
OBJ. funy ();
The execution result is very simple. The result of 5, 10, 5, and 10 is displayed.Copy codeThe Code is as follows: A. Prototype. FunX = function () {alert (x )};
A. Prototype. funy = function () {alert (y )};
The Code defines two methods: FunX and funy. So what if we need to temporarily Add a method to function?
Copy code The Code is as follows: function A (x, y)
{
This. x = X;
This. Y = y;
}
A. Prototype. FunX = function () {alert ("5 ")};
VaR OBJ = new A (5, 10 );
Alert (obj. X );
Alert (obj. y );
OBJ. FunX ();
A. Prototype. funy = function () {alert ("10 ")};
OBJ. funy ();
After running this code, we can see that the pop-up results are the same as the previous results, but we have defined both methods outside and the funy method is defined after the instantiation, so what do you see here? Obviously, when we use the obj. funy () Statement, the code will re-construct the OBJ and then execute this method. If the code is changed to this way?Copy codeThe Code is as follows: obj. funy ();
A. Prototype. funy = function () {alert ("10 ")};
Obviously, funy () won't execute the method.
Next time, I will talk about the Javascript constructor and prototype. If you have any questions or errors, please correct and discuss them.