Home > Web Front-end > JS Tutorial > body text

JavaScript constructor essential knowledge for object-oriented learning_js object-oriented

WBOY
Release: 2016-05-16 18:25:35
Original
1196 people have browsed it
Copy code 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 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?

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 . Fun 🎜>

Copy code


The code is as follows:
A.prototype.FunX = function(){alert(x)}; A.prototype.FunY = function(){alert(y)}; These two lines of code define two methods, namely FunX and FunY. So, if a situation arises now, what should we do if we need to temporarily add a method to the A function?



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:
obj.FunY(); A.prototype .FunY = function(){alert("10")}; Obviously, FunY() will not execute the method.
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.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template