Copy Code code as follows:
function A (x)
{
this.x = x;
}
var obj = new A (5);
alert (obj.x);
The code is very simple, but it's important to see a very surprising result, and obj was given an attribute x, just as we would use an instance of a class in C #. So how does this attribute occur?
Key statement: This.x=x. This sentence is to do a property of the declaration and assignment, here, we will certainly ask, this is what? Why is it possible to use This.x to declare and assign attributes?
In fact this represents the obj we just instantiated, which is equivalent to using OBJ to invoke the properties, methods, and so on in constructor a.
So, how do we define a method in the constructor?
Copy Code code 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 result of the execution is very simple, pop-up 5, 10, 5, 10 results, you can see
Copy Code code as follows:
A.prototype.funx = function () {alert (x)};
A.prototype.funy = function () {alert (y)};
These two codes define two methods, namely Funx and Funy. So if there's a situation now, what if we need to add a method to the a function temporarily?
Copy Code code 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 ();
Running this code, we can see that the pop-up results are the same as the previous results, but we have two methods are defined outside, and the method Funy is defined after the instantiation, so what do you see here? Obviously, when we use obj. Funy () statement, the code will again construct obj, and then to execute this method, if the code changes to this?
Copy Code code as follows:
Obj. Funy ();
A.prototype.funy = function () {alert ("10")};
Obviously, Funy () is not going to execute the method.
Next time, we'll talk about the constructors and prototypes of JavaScript (prototype), and if there are any questions or mistakes, please comment and discuss them.