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

Understand JavaScript classes from shallow to deep_javascript skills

WBOY
Release: 2016-05-16 19:26:12
Original
931 people have browsed it

Time: 2006-3-6
Author: Qihongting
Introduction:
Original source: www.51js.com
Description: June 15, 2004
Translation:

I have been hanging out in Wuyou Script for a while recently and responded to some posts, but I didn’t make anything for everyone to see. I felt a little uneasy, so I wrote the following thing, which should have been posted in Class Encapsulation area, considering that it is relatively cold there, and I hope this article can help more friends, so I put it here. What is the

class?
Many friends who are new to programming may not understand classes. In fact, classes are a simulation of our real world. It may be easier to understand it by calling it a "category" or "type". For example, an animal like "human" is a class, and a specific person is an instance of the class "human". There can be many instances of "human" (there are more than 6 billion people on earth), but the class "human" only has one. You might say, aren’t men and women humans too? Why can there only be one? In fact, we are going to talk about inheritance here, which will be discussed later, so please continue reading.
How to create a class?
In C, a class is declared as a class. Unlike C, JavaScript uses the same function as a function to declare it. This makes many friends who learn Jscript mix classes and functions. In Jscript There is indeed some confusion between functions and classes, but you will naturally understand it after using it for a long time. This article is written for friends who want to attack object-oriented programming, and I do not intend to discuss it too deeply at once.
Please see the definition of this class below:


function WuYouUser()
{
this.Name; }

The above The code defines a WuYouUser (worry-free user) class, which has an attribute: Name. Name is an attribute of the WuYouUser class.
A class has fixed attributes, but instances of the class have different attribute values. For example, I belong to the category "person" and my gender is male, and I have a female classmate who also belongs to the category "person" class, but her gender attribute value is female.
So how to declare an instance of a class? Very simple:

var Wo = new WuYouUser(); //Example 1: "I"
var Biyuan = new WuYouUser(); //Example 2: "Biyuan" Brother, I'm sorry... Hehe)

Class attributes
This Wo (me) is an instance of WuYouUser class, which has everything given to it by WuYouUser: Name attribute, Sex attribute and Age attribute. We can set its properties like this:

Wo.Name = "Weeping Red Pavilion";

Very simple, right? Try running

window.document.write(Wo.Name);

to see if my name is output: Qihongting?

Same as Biyuan’s properties

Biyuan.Name = "Biyuan";

Run

window.document.write(Biy uan. Name);

You can see that "Biyuan" is output, which means that Biyuan and Wo are also instances of the WuYouUser class, but they are different entities with different attribute values.

Attributes can be set to default values. Wuyou has a record of how many posts each person has posted. We also add an attribute ArticleCount for the number of posts to the WuYouUser class

function WuYouUser ()
                                                                                                            The quantity is 0, in In the code above, you can see that the property ArticleCount is directly set to 0.

You can run this code:

var Wo = new WuYouUser();
window.document.write(Wo.ArticleCount);

You can see 0 is output, indicating that we have successfully set the ArticleCount attribute to the default value of 0

Method of class
The word method is not easy to understand. I think it is easier to understand if it is described as behavior. A person has many common behaviors, such as sleeping, eating, walking, etc. Now we add a posting method to the WuYouUser class.

                                                                                                                                                    🎜>              this.NewArticle = function()                                                                                             
                                                                                                                             A button like that?
                                                                                                                                                                                                                                      . Our number of posts plus 1!
*Note: This is how the dinosaur level is added, so ... everyone posts it. . .
                                                                     >           // Now that this method is defined, let’s try it out:

var Wo = new WuYouUser();
Wo.NewArticle();
document.write(Wo.ArticleCount); You can see that the output is 1, which means we posted successfully! It’s really a moment of historical significance, one step closer to the dinosaur level.

Static properties

Static properties are also called public properties. They do not belong to instances of a certain class, but directly belong to a certain class.

For example, a Wuyou user has an attribute: the number of registered users. It belongs to the entire Wuyou user, not to Qihongting or anyone else
The declaration method of static attributes is:

Class name.prototype.Attribute name = Attribute value;

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

WuYouUser.prototype.Count = 0;

So how to read it? There are two methods:

1. Directly use WuYouUser.prototype.Count
2. Use Wo.Count

There is no difference between the two, both get 0

Although there are two reading methods, you have to be particularly careful when changing it. Please see the code below

var Biyuan = new WuYouUser();
WuYouUser.prototype. Count ;
document.write(Wo.Count);
document.write(Biyuan.Count);


You will find that the Count attribute of both is 1, that is to say WuYouUser.prototype.Count changes the corresponding properties that will affect each instance. In fact, the principle is that the Count properties of Wo and Biyuan and WuYouUser.prototype.Count are basically the same!

Now look at another piece of code:


var Biyuan = new WuYouUser();

Biyuan.Count; // Pay special attention here, this is direct Change Biyuan’s Count property
document.write(Biyuan.Count); // Output 1
document.write(WuYouUser.prototype.Count); // Output 0
document.write(Wo.Count) ; //Same output is 0, why?


You can see that if you directly modify the static attribute value of an instance, will the static attributes of other instances or even classes be out of sync with it? This is because when directly modified, the instance will generate an attribute Count belonging to the instance. At this time, Biyuan.Count is no longer the same as WuYouUser.prototype.Count, nor is it the same as Wo.Count. This Count The attribute belongs to Biyuan himself, and any changes to it in the future will only affect it.

Therefore, if there is no special need, it is recommended to use WuYouUser.prototype.Count uniformly when reading or assigning, so as to be foolproof!


Static method
Similar to static properties, it also has another name: public method, which also belongs to the class itself.

The way to define a static method is:

Class name. Method name = function (parameter 1, parameter 2...parameter n)
{
//Method code WuYouUser.prototype.Count ;
It also has two methods:

1. Directly use WuYouUser.prototype.AddOne()
2. Use AddOne() of a certain instance

There is no difference between these two methods :

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(); 2
document.write(Biyuan.Count); // 2

//It can be seen that the effect is the same whether using Wo.AddOne() or WuYouUser.prototype.AddOne(). It is to add 1 to WuYouUser.prototype.Count
Now look at a piece of code:

function NewClass() // Since the WuYouUser class above is not suitable for the code of this example, I declared a new class NewClass
                                                                                                             {
this.Name = NewName;
}

var Wo = new NewClass();
Wo.ChangeName("Zheng Yuntao"); //My real name


You can see that Wo.Name has indeed changed to "Zheng Yuntao". This method seems to work, but is there any secret in it?
Look at the code below. We still have the same definition of the class and ChangeName, but change the code below:

.write(NewClass.Name); //undefined, that is, undefined
document.write(NewClass.prototype.Name); //Zheng Yuntao
var Wo = new NewClass();
document.write( Wo.Name); //Weeping Red Pavilion


You can see that we did not define the static property NewClass.prototype.Name, but the compiler added one for us.
But look at the output Wo.Name below. It is not "Zheng Yuntao", but the original default value "Weeping Red Pavilion". What does it mean?
It’s actually very simple. Look at the definition of NewClass, which already has the Name attribute, so I also have my own Name attribute, which is not the same as NewClass.prototype.Name, so it’s still like that.

So why can the Wo.Name property be changed even if the previous example runs Wo.ChangeName("Zheng Yuntao")? In fact, it is the same as changing the value of Wo.Count here. The compiler automatically adds a method ChangeName to Wo. This method code is the same as NewClass.prototype.ChangeName, but Wo.ChangeName is unique to the Wo instance, and Not NewClass.prototype.ChangeName!

Analysis shows that in static methods, try not to use keywords like this to refer to the properties of the instance itself, unless you have a special purpose and can clearly understand the operating mechanism here!

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


NewClass.ChangeName = function(This,NewName) //Note here It’s This, not this
                                                                                                                             Constructor, let’s look at the code below: >              alert(this.Name); The definition of a class not only defines its properties and methods, but also can add some code, and these codes are the codes of the constructor of the class, which are executed during the instance declaration process!
In fact, class attributes and class methods are defined in the constructor. Look at the code below:


function WuYouUser()
this .Name = "Crying Red Pavilion";
          return;                             Document.write(Wo.Name ; The Sex attribute is after return;, and the constructor of the WuYouUser class stops running when it encounters return. In other words, the line this.Sex = "Male"; is not executed, that is, the Sex attribute is not defined at all!
The constructor can have parameters, and the parameter values ​​are passed in when declaring the instance:

function WuYouUser(Name)
This.Name = Name;
}
        var Wo = new WuYouUser("囧红丁"); 
                                                                                                                                         Document.write (Wo. Name); After setting 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 the sum of 12 and 23, 35
var Obj = new Sum(12,23);
document.write(Obj.a) // 12
document.write(Obj.b) // 23


It feels amazing, right? As I write this article, I feel it’s quite amazing, haha!

But it is strongly recommended not to use a class as a function! If what you need is a function, please write it directly as a function instead of a class to avoid confusion.

Inheritance
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 inheritance. mechanism.

At the beginning of the article, we talked about men and women. These are also two different classes, but they have the same attributes and methods. These same characteristics come from the "person" class. Change In other words, men and women inherit all the characteristics of "people"! But men and women are different, and inheritance in programming languages ​​is the same. If a class A inherits another class B, then class B is the parent class of class A, and class A is a derived class of class B, also known as as a subcategory. For example, man is a derived class of human, and human is the parent class of man. The highest level class is called the base class. If you imagine it, you can understand that men inherit from people, boys inherit from men, people are the base class of boys, and men are the father class of boys.
Outside: Multi -inheritance

Here involves a multi -inheritance topic, but if you just learn JavaScript, there is no need to watch it, because JavaScript does not provide multiple inheritance, there is no kind of accurate to put Simple and standard way to implement multiple inheritance (actually there is a way to achieve it, it's just a little more troublesome, and it's really not necessary).

There is a concept of multiple inheritance in C. We are discussing JavaScript here, so we are not going to talk about it. I just want to talk about some of its ideas for reference.

In the boy’s inheritance problem above, the boy actually not only inherits from the man, but also inherits from the child class (both boys and girls). Therefore, it inherits two classes at the same time: man With boys, this is called multiple inheritance.

Okay, let’s stop this question and let’s return to the topic.

Let’s first look at the definition of the first class:                                                                                                                       .Name);
}

// This class defines a attribute name. The default value is "Weeping Red Pavilion"

// Now see the definition of the second class:

function B()
{
this.Sex = "Male";
alert(this.Sex);
} }

//Definition There is an attribute Sex, the default value is "Male"

//The way of inheritance is subclass.prototype = new parent class();
//Now let's let class B inherit class A:

B.prototype = new A();

                                                                                                                                      ", then display "male"

It can be seen from the above results that class B inherits class A, has the attribute Name of class A, and executes the constructor of class A, and the constructor of class A Executed before the constructor of class B is executed. Therefore, we can use this to implement the method of overriding the parent class and resetting the default value of a certain attribute of the parent class: ";
this.Show = function()
" }
alert(this.Name);
}

function B()
{
this.Name = "Zheng Yuntao";
this.Show = function()
                                                                                                                                                     Show method");
                              ; = new B();
Obj.Show();

As a result, three warning windows appeared. The first content was Qihongting, which was the execution of alert(this.Name) in the constructor of class A. At that time, the Name attribute value was still there. It is "Crying Red Pavilion" because the constructor of class B has not been executed yet. The second content is "Zheng Yuntao". This is the alert(this.Name) in class B because the Name is reassigned in the constructor of class B. For "Zheng Yuntao". Finally, Obj.Show() is called, and the Show in the Show method of class A is not executed (displaying "This is the Show method of class A"), but the Show of class B is executed (displaying "This is the Show method of class B"). Show method"), it is obvious that the Show method has been overridden.

The attributes and methods of a class as an object (I don’t know how to express it concisely, so I used such a long title)
I don’t know if talking about this topic here is a bit confusing, but I think it is This article would not be complete without talking about it, because the purpose of the article is to make people understand all aspects of classes.

After reading the title of this section, you may find it strange that a class is a class, so how can it be "used as an object"? In JavaScript, everything is an object, including classes! Objects can have properties and methods, and classes can also have them. However, this is very easy to be confused with the static properties and static methods mentioned above, so you must carefully understand the difference between the two!

Define a class:
function WuYouUser()
{
this.Name = "Crying Red Pavilion";
}

​​​​//Define the class as a Object attributes:

WuYouUser.Url = "http://www.51js.com"; //The definition of static attributes is: 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 the undefined here

It can be seen from here that the Url attribute is owned by WuYouUser itself, and changing it has nothing to do with other classes and its subclasses!

There is only one way to reference the attributes of a class, which is the class name. Attribute name. The same goes for changing it.

Method when defining a class as an object:


WuYouUser.ChangeUrl = function()
"http://51js.com ";
                                                                                                                                                                                                                                                              Because the ChangeUrl method belongs to the object WuYouUser, this refers to WuYouUser itself!

//You can try running the code below:

document.write(WuYouUser.Url); // http://www.51js.com
WuYouUser.ChangeUrl() ;
document.write(WuYouUser.Url); // http://51js.com


Obviously ChangeUrl directly modifies the value of WuYouUser.Url, so http:// can be output later. 51js.com

If you don’t understand this section, don’t worry. In programming, many things can only be understood but not expressed in words, and I don’t have the eloquence to explain clearly. I just need to write more in the future. When writing code, you will naturally realize this by using classes. You can also take a look at the JSVM code. Almost every class in it has properties and methods that use the class as an object
Although this is in javascript, It should be helpful to understand the concept of classes! [sweat] Hope it helps

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