function A(x)
{
this.x = x;
}
var obj = new A(5);
alert(obj.x);
This code is very simple, but what is important for us is to look at We arrived at a very surprising result. Obj was assigned an attribute x, just like when we use an instance of a class in C#. So how did this property come about?
Key statement: this.x=x. This sentence is to declare and assign an attribute. Here, we will definitely ask, what is this? Why can you use this.x to declare and assign attributes?
In fact, this represents the obj we just instantiated, which is equivalent to us using obj to call the properties, methods, etc. in constructor A.
So, how do we define a method in the constructor?
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 . Fun 🎜>
Copy code
The code is as follows:
Copy code
The code is as follows:
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();
Running this code, we can see that the pop-up result is still the same as the previous result, but we will Both methods are defined outside, and the method FunY is defined after instantiation, so do you see anything here? Obviously, when we use the obj.FunY() statement, the code will re-construct obj and then execute this method. So what if the code is changed to this?
Copy code
The code is as follows:
Next time, I will talk about JavaScript constructors and prototypes. If you have any questions or errors, please feel free to make corrections and discuss them.