Learn about JavaScript _javascript skills from shallow to deep

Source: Internet
Author: User
Tags inheritance
Time: 2006-3-6


Author: Weeping Red Pavilion


Brief introduction:


Original source: www.51js.com


Description: June 15, 2004


Translation:





Recently in the worry-free script mixed for a while, replying to some posts, I did not make anything to let everyone see, the mind some uneasy, so wrote a little things below, should have been sent in the class packaging area, considering where the more cold, and this article I hope to be able to help more friends, so put here.





What is a class?


Many friends who have just come in contact with programming may not understand the class, but the class is a simulation of our real world, and it may be easier to interpret it as "category" or "type". For example, "Man" The animal is a class, and a specific person is a "person" an example of this class, "man" can have many instances (Earth people more than 6 billion), but the "person" this class only one. You might say that man and woman are not human? How can there be only one? In fact here to talk about a succession of things, behind the talk, please continue to look down.


How do I build a class?


In C + +, a class is declared with classes, and JavaScript differs from C + + in that it uses function-like functions to declare it, which allows many friends of JScript to mix classes with functions, and in JScript functions and classes do mix, But the use of a long time will naturally understand that this article is intended to attack object-oriented programming friends and write, do not intend to discuss too deeply.


See the definition of this class below:








function Wuyouuser ()


{


This. Name; Name


}





The code above defines a wuyouuser (worry-free user) class that has an attribute: name. Name is an attribute of the Wuyouuser class.


A class has a fixed attribute, but the instance of the class has different attribute values, just as I belong to "person", the gender is male, and I have a female classmate, she also belongs to "person" class, but her sex attribute value is female.


So how do you declare an instance of a class? Very simple:








var Wo = new Wuyouuser (); Example one: "I"


var Biyuan = new Wuyouuser (); Example two: "Bi Yuan" (Biyuan, sorry ...) Hey





Properties of the class


This wo (me) is an instance of the Wuyouuser class, which has everything wuyouuser gives it: the Name property, the Sex property, and the Age property, which we can set its properties in this way:





Wo.name = "Weeping Red Pavilion";





It's simple, isn't it? Try to run.





Window.document.write (Wo.name);





See, is not the output of my name: Weeping Red Pavilion?





Also set up the attributes of Brother Bi





Biyuan.name = "bi yuan";





Run





Window.document.write (Biyuan.name);





You can see the output of "bi-yuan", it also shows that Biyuan and Wo are the same Wuyouuser class, but are different entities, with different attribute values.





Properties can be set by default, worry-free record of how many posts we each sent, we also give the Wuyouuser class to add a number of posts attributes Articlecount





function Wuyouuser ()


{


This. Name;


This. Articlecount = 0;


}





A worry-free new user just after registering his post number is 0, in the above code can be seen directly to the property Articlecount set a value of 0.





You can run a code like this:





var Wo = new Wuyouuser ();


Window.document.write (Wo.articlecount);





You can see the output is 0, which indicates that the Articlecount property was successfully set by the default value of 0





Methods of the class


The word "method" is not very well understood, and I think it is easier to understand it. A person has a lot of common behavior, such as sleeping, eating, walking, and so on, now we add a method of posting to the Wuyouuser class.








function Wuyouuser ()


{


This. Name;


This. Articlecount = 0;





This. Newarticle = function ()


{


/*


*


* Specific how to post we all know, is not typing, gaga picture and then click the Save button?


* There is no need to write the code on how to post it, we only need to understand the definition and use of the method.


* We are here to achieve one of the simplest functions, but also a very important function: to our number of posts added 1!


* Note: The dinosaur grade is so added, so ... Let's all go to the posts ...


*/





This. articlecount++;


}


}





Now that we've defined this method, let's try to see how it works:





var Wo = new Wuyouuser ();


Wo.newarticle ();


document.write (Wo.articlecount); You can see the output of 1, indicating that we have succeeded in posting! It's a moment of historic remembrance, and it's a step closer to the dinosaur hierarchy.





Static properties





A static property, also known as a public property, does not belong to an instance of a class, but rather belongs directly to a class.





For example, worry-free users have a property: the number of registered users, it belongs to the entire worry-free users, not belong to the Weeping Red Pavilion or whose


The declaration method for a static property is:





Class name. prototype. property name = attribute value;





For example, define a number of registered users for the Wuyouuser class count:





WuYouUser.prototype.Count = 0;





So how do you read it? There are two ways of doing this:





1. Direct use of WuYouUser.prototype.Count


2. Use of Wo.count





There is no difference between the two, is to get 0





Although there are two ways to read, you have to be very careful when changing it, look at the code below








var Biyuan = new Wuyouuser ();


wuyouuser.prototype.count++;


document.write (Wo.count);


document.write (Biyuan.count);








You'll find that both of the count attributes are 1, which means that WuYouUser.prototype.Count changes the corresponding attributes that affect each instance, but the principle is Wo, The Biyuan Count property is the same as WuYouUser.prototype.Count!





Now look at another piece of code:








var Biyuan = new Wuyouuser ();





biyuan.count++; Pay special attention here, this is directly changing the Biyuan Count property


document.write (Biyuan.count); Output 1


document.write (WuYouUser.prototype.Count); Output 0


document.write (Wo.count); Same output 0, why?








You can see that if you modify the static property value of an instance directly, then other instances or even the static properties of the class are not synchronized with it? This is because when directly modified, the instance generates a property count that belongs to the instance. This time Biyuan.count no longer with WuYouUser.prototype.Count is the same, also not with Wo.count is the same, this count attribute belongs to Biyuan own all, later changed it also only affects itself.





Therefore, if not a special need, it is recommended that no matter in the reading or assignment, the unified use of WuYouUser.prototype.Count such a way to achieve foolproof!








static method


Like a static property, it has a different claim: The public method, also belongs to the class itself.





Static methods are defined by:





Class name. Method name = function (parameter 1, parameter 2 ...). Parameter n)


{


Method code


}





We're going to define a worry-free user class. Register a new user static method:





WuYouUser.prototype.AddOne = function ()


{


The same specific code does not write, add 1 to the static property count, indicating a number of registered users


wuyouuser.prototype.count++;


}





Now let's look at how to use it, and there are two ways:





1. Direct use of WuYouUser.prototype.AddOne ()


2. Use an instance of AddOne ()





The two approaches are no different:








var Wo = new Wuyouuser ();


var Biyuan = new Wuyouuser ();


document.write (WuYouUser.prototype.Count); 0





Wo.addone ();


document.write (WuYouUser.prototype.Count); 1


document.write (Wo.count); 1


document.write (Biyuan.count); 1





WuYouUser.prototype.AddOne ();


document.write (WuYouUser.prototype.Count); 2


document.write (Wo.count); 2


document.write (Biyuan.count); 2





It can be seen whether the use of Wo.addone () or WuYouUser.prototype.AddOne () effect is the same, is to WuYouUser.prototype.Count plus 1


Now look at a piece of code:





function Newclass ()//Because the above Wuyouuser class is not appropriate for this example code, I declare a new class Newclass


{


This. Name = "Weeping Red Pavilion"; The default value here is my name


}





NewClass.prototype.ChangeName = function (NewName)


{


This. Name = NewName;


}





var Wo = new Newclass ();


Wo.changename ("Cheng"); my real name.








Can see Wo.name indeed has become "Cheng", this method seems to be able to use, but inside is not inside have the secret?


Then look at the code below, the definition of the class and the definition of changename we still, but change the following code:








NewClass.prototype.ChangeName ("Cheng");


document.write (Newclass.name); Undefined, that is undefined


document.write (NewClass.prototype.Name); Cheng


var Wo = new Newclass ();


document.write (Wo.name); Weeping Red Pavilion








You can see that we don't define NewClass.prototype.Name this static property, but the compiler adds one to ourselves.


But look at the bottom of the output wo.name, it is not "Cheng", but the original default value "Weeping Red Pavilion", explains what?


In fact it is very simple, look at the definition of Newclass already have name this attribute, so Wo also has its own name attribute, it and NewClass.prototype.Name is not the same, so it is the same.





So why did the previous example run Wo.changename ("Cheng") but was able to implement the change Wo.name attribute? In fact here is the same as changing the value of Wo.count, the compiler automatically adds a method to Wo ChangeName, this method code is the same as NewClass.prototype.ChangeName, but Wo.changename is unique to this instance of Wo, not the new class.prototype.changename!





Analysis can know that in a static method try not to use this keyword to refer to the properties of the instance itself, unless you have a special purpose, and can clearly understand the side of the operating mechanism!





If you really need to use this in a static method, you can simply pass this as a parameter:








Newclass.changename = function (this,newname)//Note this is this, not this


{


THIS.name = NewName;


}





Constructors


A class in the initialization is actually a function of the execution process, this function is the constructor, we look at the following code:








function Wuyouuser ()


{


This. Name = "Weeping Red Pavilion"; The default definition is weeping Red Pavilion


Alert (this. Name);


}


var Wo = new Wuyouuser ();//You can see a window showing three words of weeping Red Pavilion








You can see that the definition of a class not only defines its properties and methods, but also adds code that is the code for the constructor of the class that is executed in the instance declaration process!


In fact, the class's Properties and class methods are defined in the constructor, looking at the code below:








function Wuyouuser ()


{


This. Name = "Weeping Red Pavilion";


Return


This. Sex = "male";


}


var Wo = new Wuyouuser ();


document.write (Wo.name); Weeping Red Pavilion


document.write (Wo.sex); Undefined, that is undefined











What can you tell? The Sex property is after return, and the constructor of the Wuyouuser class stops running when it encounters return, in other words this. Sex = "male"; this line is not executed, that is, the Sex attribute is not defined at all!


Constructors can have parameters, and parameter values are passed in when the instance is declared:





function Wuyouuser (Name)


{


This. name = name;


}


var Wo = new Wuyouuser ("Weeping Red Pavilion");


document.write (Wo.name); Weeping Red Pavilion








Constructors do not need to return a value, but if you set the return value, you can use it as a function. function Sum (A, B)


{


THIS.A = A;


this.b = b;


return THIS.A + this.b;


}


document.write (Sum (12, 23)); The output is 12 and 23 and 35.


var Obj = new Sum (12,23);


document.write (OBJ.A)//12


document.write (OBJ.B)//23








It's kind of amazing, isn't it? I write this article is written to write also feel very wonderful, hehe!





But it is strongly recommended that you do not use a class as a function! If you need a function, write the function directly instead of writing to the class so you don't get confused.





Inherited


The word inheritance is very important in object-oriented programming, although JavaScript is not a real object-oriented language, it is an object-based language like VB, and it also provides an inheritance mechanism.





The article begins with the men and women, which are also two different classes, but have the same attributes and methods, and these same characteristics come from the category of "person", in other words, men and women inherit all the characteristics of "human"! But men and women have different places, the same in programming languages, a Class A inherits another Class B, then Class B is the parent class of Class A, and Class A is the derived class of Class B, also called subclasses. For example, a man is a derivative of a man, and a man is the parent of a man. The highest class is called the base class, and you can imagine that the man inherits from the man, the boy inherits from the man, the man is the base of the boy, and the man is the father of the boy.


Beyond: Multiple Inheritance





There's a multiple inheritance topic here, but if you're just learning JavaScript, there's no need to look, because JavaScript doesn't provide multiple inheritance, and it's not a simple and standard way to implement multiple inheritance (there's a way to do it, but it's a bit cumbersome, And it's really not necessary).





In C + + there is the concept of multiple inheritance, here is the discussion of JavaScript, so do not intend to speak, just say it's a little bit of thought for reference.





In the inheritance of the boy above, the boy is not only inherited from the man, but also inherited from the child (there are boys, there are girls) this class, so it inherited two classes: men and boys, this is called multiple inheritance.





OK, that's the problem, we're back to the subject.





First look at the definition of the first class:


function A ()


{


This. Name = "Weeping Red Pavilion";


Alert (this. Name);


}





This class defines a property name, and the default value is "Weeping Red pavilion."





Now look at the definition of the second class:





function B ()


{


This. Sex = "male";


Alert (this. SEX);


}





A property sex is defined, and the default value is "male"





The way to inherit is subclasses. prototype = new parent ();


Now let's get Class B to inherit category A:





B.prototype = new A ();











Run this section of code:





var Obj = new B (); First open the warning window to display "Weeping Red Pavilion", and then show "Male"





You can see from the results above that Class B inherits the Class A, owns the property name of Class A, and executes the constructor of Class A, and the constructor of Class A is executed before the constructor of Class B executes. So we use this to implement a method that overrides the parent class and to reset the default value of a property of the parent class:








function A ()


{


This. Name = "Weeping Red Pavilion";


This. Show = function ()


{


Alert ("This is the Show method for Class A");


}


Alert (this. Name);


}





function B ()


{


This. Name = "Cheng";


This. Show = function ()


{


Alert ("This is the show method of Class B");


}


Alert (this. Name);


}


B.prototype = new A ();


var Obj = new B ();


Obj.show ();





The result is three warning windows, the first of which is the Weeping Red Pavilion, which is the alert in the constructor of Class A (this. Name), at which point the Name property value is also "weeping Red Pavilion" because the constructor for Class B is not yet executed, and the second content is "Cheng", which is alert in class B (this. Name), because the name is assigned the value "Cheng" in the constructor of Class B. In the end it was called obj.show (), performing the show (showing "This is a shows method of Class A") instead of the A-class display method, but performing the show of Class B (showing "This is the B-class display Method"), and it was obvious that the shows method was rewritten.





The properties and methods of a class as an object (do not know how to express it succinctly, so it takes so long a topic)


I don't know if it's a bit confusing to talk about this topic, but I don't think this article is complete, because the purpose of the article is to make people understand all aspects of the class.





Read this section of the topic, perhaps you will find it strange that class is class, how can "as an object"? In JavaScript, everything is an object, including classes! objects can have attributes, can have methods, and classes can also have, but this is very easy to talk about static properties and static methods confused, so to carefully see the difference between the two!





Define a class:


function Wuyouuser ()


{


This. Name = "Weeping Red Pavilion";


}





Defines the properties of a class when it is an object:





Wuyouuser.url = "http://www.51js.com"; Static properties are defined as: WuYouUser.prototype.Url = "http://www.51js.com";


var Wo = new Wuyouuser ();


document.write (Wuyouuser.url); Http://www.51js.com


document.write (Wo.url); Undefined, that is not defined! Note that there is no definition





From here you can see that the URL this property is Wuyouuser from all, changed it and other classes and its subclasses completely irrelevant!





There is only one way to reference a property of a class, that is, the class name. property name, change it also.





Defines how a class is treated as an object:








Wuyouuser.changeurl = function ()


{


This. URL = "http://51js.com";


}





You might find it strange, what's this here? Because Changeurl this method belongs to the object Wuyouuser, so this refers to wuyouuser itself!





You can run the code below to try:





document.write (Wuyouuser.url); Http://www.51js.com


Wuyouuser.changeurl ();


document.write (Wuyouuser.url); Http://51js.com








Obviously changeurl directly modifies the value of the Wuyouuser.url, so the http://51js.com can be output behind.





If you don't see this section, also do not worry, programming, many dongdong can only understand can not say, and I have no eloquence, said not clear, as long as the later write code, more use class will naturally experience this some, and can go to see JSVM code, Almost every class in it is useful to the properties and methods of a class as an object


This is in JavaScript, but it should be helpful to understand the concept of Class! [Sweat] hope it will help.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.