Understand JavaScript classes and objects

Source: Internet
Author: User

What is a class?

 

 

Many friends who are new to programming may not understand the class. In fact, the class is a simulation of our real world. It may be easier to say "category" or "type. For example, an animal like "man" is a class, and a specific person is an instance of "man". "Man" can have many instances (more than 6 billion people on Earth ), however, the "person" class only has one. Maybe you will say that men and women are not people too? How can there be only one? In fact, here we need to talk about inheritance. We will talk about it later. Please continue with this article.

How to create a class?
In C ++, a class is declared as a class. Javascript is different from C ++. It uses the same function as a function for declaration, this allows many JScript learners to mix classes and functions. In JScript, functions and classes are indeed mixed, but after a long time of use, they will naturally understand this article.ArticleIt is written for a friend who wants to attack object-oriented programming. I don't plan to discuss it too deeply at once.
See the definition of this class below:

Function wuyouuser ()
{
This. Name; // name
}

AboveCodeDefines a wuyouuser class, which has a property: Name (name ). Name is an attribute of the wuyouuser class.
A class has fixed attributes, but its instances have different attribute values, just as I belong to the "person" class, and the gender is male, while I have a female classmate, she also belongs to the "person" class, but her gender attribute value is female.
So how to declare an instance of a class? Very simple:

VaR Wo = new wuyouuser (); // instance 1: "I"
VaR Biyuan = new wuyouuser (); // instance 2: "Biyuan" (Biyuan brother, sorry... Hey hey)

Class attributes

This Wo (I) is an instance of the wuyouuser class. It owns everything that wuyouuser gives it: name, sex, and age, we can set its attributes like this:
WO. name = "Weeping Red Pavilion";
is it simple? Try to run
zookeeper Doc ument. Write (WO. Name);
to see if my name is output: Weeping Red Pavilion?
set the attributes of Biyuan brother
Biyuan. name = "Biyuan";
RUN
zookeeper Doc ument. write (Biyuan. name);
The result shows that Biyuan and wo are instances of the wuyouuser class, but they are different entities with different attribute values.
you can set the default value for the attribute. There is no worries about how many posts are automatically posted, we also add an attribute articlecount for the number of posts to the wuyouuser class
function wuyouuser ()
{< br> This. name;
This. articlecount = 0;
}< br>
the number of posts sent by a new carefree user after registration is 0, in the code above, we can see that the value of articlecount is set to 0.
run the following code:
var Wo = new wuyouuser ();
invalid variable Doc ument. write (WO. articlecount);
0 is displayed, indicating that the default value of the articlecount attribute is 0.

Class Method

The term "method" is not easy to understand. I think it is easier to say "behavior. A person has many common behaviors, such as sleeping, eating, walking, etc. Now we add a posting method to the wuyouuser class.

Function wuyouuser ()
{
This. Name;
This. articlecount = 0;

This. newArticle = function ()
{
/*
*
* We All Know How To post images. Isn't it just typing, adding images and clicking save or something like that?
* You do not need to write the code about how to post it here. All you need to know is how to define and use the method.
* Here we implement a simple and important function: Add 1 to the number of posts!
* Note: The dinosaur level is added in this way, so ...... Let's talk about it...
*/

This. articlecount ++;
}
}

Now that we have defined this method, let's try it:

VaR Wo = new wuyouuser ();
Wo. newArticle ();
Document. Write (WO. articlecount );

The output is 1, indicating that the post is successfully posted! It's really a moment of historical commemorative significance. It's a step closer to the level of dinosaurs.

Static attributes

Static attributes, also known as public attributes, do not belong to an instance of a class, but directly belong to a class.

For example, a carefree user has a property: the number of registered users, which belongs to the entire carefree user, rather than to the Weeping Red Pavilion or who
The static attribute declaration method is as follows:

Class Name. Prototype. property name = property value;

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

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 must be very careful when changing it. Please refer to the following code.

VaR Biyuan = new wuyouuser ();
Wuyouuser. Prototype. Count ++;
Document. Write (WO. Count );
Document. Write (Biyuan. Count );

You will find that both the Count attribute is 1, that is, wuyouuser. prototype. the change in count will affect the corresponding attributes of each instance. In fact, the principle is that the Count attribute of Wo and Biyuan and wuyouuser. prototype. count is the same!

Now let's look at another piece of code:

VaR Biyuan = new wuyouuser ();

Biyuan. Count ++; // note that this directly changes the Count attribute of Biyuan.
Document. Write (Biyuan. Count); // output 1
Document. Write (wuyouuser. Prototype. Count); // output 0
Document. Write (WO. Count); // the same output is 0. Why?

We 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 the instance is directly modified, the instance will generate a property count that belongs to the instance. At this time, Biyuan. count is no longer associated with wuyouuser. prototype. count is the same, not with Wo. count is the same. This count attribute belongs to Biyuan, and it will only affect itself if it is changed later.

Therefore, if it is not necessary, we recommend that you use wuyouuser. Prototype. count in a unified manner no matter when reading or assigning values!

Static Method

Similar to static attributes, it also has a public method, which also belongs to the class itself.

Static methods are defined as follows:

Class Name. method name = function (parameter 1, parameter 2... parameter n)
{
// Method code
}

Now let's define a carefree user-class static method for registering new users:

Wuyouuser. Prototype. addone = function ()
{
// *** If no specific code is written, add 1 to the static attribute count, indicating that there are more registered users.
Wuyouuser. Prototype. Count ++;
}

Now let's take a look at how to use it. There are also two methods:

1. directly use wuyouuser. Prototype. addone ()
2. Use addone () of an instance ()

There is no difference between the 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 ();
Document. Write (wuyouuser. Prototype. Count); // 2
Document. Write (WO. Count); // 2
Document. Write (Biyuan. Count); // 2

It can be seen that the effects of both Wo. addone () and wuyouuser. Prototype. addone () are the same, and 1 is added to wuyouuser. Prototype. Count.

Now let's look at a piece of code:
Function newclass () // because the above wuyouuser class is not suitable for the code in this example, 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 ("Zheng yuntao"); // my real name

We can see that wo. name has indeed changed to "Zheng yuntao". This method seems to be usable, but is there any Tianji in it?
Let's look at the code below. The definition of the class and the definition of changename are the same, but the code at the bottom of the handler is changed:

Newclass. Prototype. changename ("Zheng yuntao ");
Document. 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

We can see that we have not defined the static attribute newclass. Prototype. Name, but the compiler adds one to ourselves.
But let's look at the output of "Wo. Name" below. It is not "Zheng yuntao", but the original default value "Weeping hongting". What does it mean?
In fact, it is very simple. Check that the newclass definition already has the name attribute. Therefore, wo also has its own name attribute, which is similar to newclass. prototype. the name is not the same.

So why can the previous example run Wo. changename ("Zheng yuntao") to change the wo. Name attribute? In fact, here we will change wo. the value of count is the same principle. The Compiler automatically adds a method changename to Wo. This method code is similar to newclass. prototype. changename is the same, but wo. changename is unique to this instance, not newclass. prototype. changename!

Analysis can tell you that in static methods, try not to use keywords such as this to reference the attributes of the instance, unless you have a special purpose and can clearly understand the running mechanism here!

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

Newclass. changename = function (this, newname) // note that this is not this
{
This. Name = newname;
}

Constructor

A class is actually a function execution process during initialization. This function is a constructor. Let's look at the code at the bottom of the handler:

Function wuyouuser ()
{
This. Name = "Weeping Red Pavilion"; // It is defined as Weeping Red Pavilion by default.
Alert (this. Name );
}
VaR Wo = new wuyouuser (); // you can see the words Weeping Red Pavilion in a window.

It can be seen that the definition of a class not only defines its attributes and methods, but also some code, which is the code of the constructor of the class, executed during instance declaration!
In fact, the attributes and methods of a class are defined in the constructor. See the following code:

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 I see? The sex attribute is after return; and The wuyouuser class constructor stops running when return is encountered. In other words, this. sex = "male"; this line is not executed, that is, the sex property is not defined at all!

A constructor can have parameters that are passed in when an instance is declared:
Function wuyouuser (name)
{
This. Name = Name;
}
VaR Wo = new wuyouuser ("Weeping Red Pavilion ");
Document. Write (WO. Name); // Weeping Red Pavilion

The constructor does not need to return values. However, if you set a return value, you can use it as a function.
Function sum (A, B)
{
This. A =;
This. B = B;
Return this. A + this. B;
}
Document. Write (sum (12, 23); // The output values are 12, 23, and 35.
VaR OBJ = new sum (12, 23 );
Document. Write (obj. a) // 12
Document. Write (obj. B) // 23

It's amazing, right? I wrote this article and wrote it. It's amazing, huh, huh!

However, we strongly recommend that you do not use a class as a function! If you need a function, directly write it as a function instead of a class to avoid confusion.

Inheritance

Inheritance is very important in Object-Oriented Programming. Although Javascript is not really an object-oriented language, it is an object-based language like VB, it also provides an inheritance mechanism.

At the beginning of the article, we talked about men and women. This is also two different classes, but they have the same attributes and methods, these identical features come from the "person" class. In other words, men and women inherit all the features of "person! However, men and women are different,Programming LanguageClass A inherits from another class B. Class B is the parent class of Class A, and Class A is the derived class of Class B, also known as a subclass. For example, a man is a derived class of a man, and a man is the parent class of a man. The class at the highest level is called the base class. You can imagine that men inherit from people, boys inherit from men, and men are the base classes of boys, and men are the father classes of boys.


Extra: Multi-Inheritance

Here is another topic of Multi-inheritance, but if you only want to learn JavaScript, you do not need to take a look at it, because JavaScript does not provide multi-inheritance, to be accurate, there is no simple and standard method to implement multi-inheritance (in fact, there is a way to achieve it, but it is a little troublesome and indeed not necessary ).

In C ++, there is a concept of multi-inheritance. Here we discuss JavaScript, so we don't want to talk about it, just a little bit of it for reference.

In the Inheritance Problem of boys above, boys not only inherit from men, but also from children (boys and girls). Therefore, they inherit two classes at the same time: men and boys are called multi-inheritance.

Okay, let's move back to the topic.

First, let's look at the definition of the first class:

Function ()
{
This. Name = "Weeping Red Pavilion ";
Alert (this. Name );
}

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

Now let's look at the definition of the second class:

Function B ()
{
This. Sex = "male ";
Alert (this. Sex );
}

Defines an attribute sex. The default value is "male"

The Inheritance Method is subclass. Prototype = new parent class ();
Now let's let Class B inherit Class:

B. Prototype = new ();



Run the following code:

VaR OBJ = new B (); // first, open the warning window to display "Weeping Red Pavilion" and then "male"

From the above results, we can see that Class B inherits Class A, has the attribute name of Class A, and executes the constructor of Class, in addition, Class A constructor is executed before class B constructor is executed. Therefore, we can use this method to override the parent class and reset the default value of an attribute of the parent class:

Function ()
{
This. Name = "Weeping Red Pavilion ";
This. Show = function ()
{
Alert ("this is the show method of Class ");
}
Alert (this. Name );
}

Function B ()
{
This. Name = "Zheng yuntao ";
This. Show = function ()
{
Alert ("this is the show method of Class B ");
}
Alert (this. Name );
}

VaR OBJ = new B ();
OBJ. Show ();

The result shows three warning windows. The first one is Weeping Red Pavilion, which is the alert (this. name). At that time, the value of the name attribute was "Weeping Red Pavilion", because the Class B constructor has not been executed, and the second content was "Zheng yuntao ", this is the alert (this. name), because the name in the Class B constructor is assigned with "Zheng yuntao ". Finally, obj is called. show (), execute show (Show "this is the show method of Class A") not in the show method of Class "), instead, the show method of Class B is executed (display "this is the show method of Class B"). Obviously, the show method is overwritten.


Attributes and methods when a class is used as an object (I don't know how to express it concisely, so I used such a long question)

 

I don't know whether to talk about this topic here is a bit confusing, but I think it is incomplete not to talk about this article, because the purpose of this article is to clarify all aspects of the class.

After reading the questions in this section, you may find it strange that a class is a class. How can you "act as an object? In JavaScript, everything is an object, including a class! Objects can have attributes, methods, and classes. However, it is very easy to confuse static attributes with static methods mentioned above. Therefore, you must carefully check the differences between the two!

Define a class:
Function wuyouuser ()
{
This. Name = "Weeping Red Pavilion ";
}

Attributes when defining a class as an object:

Wuyouuser. url = "http://www.51js.com"; // The static property is 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, undefined! Note that the definition is not defined here.

From this we can see that the URL property is owned by wuyouuser, and it has nothing to do with other classes and its subclass!

There is only one way to reference a class property, that is, the class name. attribute name. The same is true for changing it.

Method for defining a class as an object:

Wuyouuser. changeurl = function ()
{
This. url = "http://51js.com ";
}

You may find it strange. What is this here? Because the changeurl method belongs to the wuyouuser object, this refers to the wuyouuser itself!

You can run the following code to try:

Document. Write (wuyouuser. url); // http://www.51js.com
Wuyouuser. changeurl ();
Document. Write (wuyouuser. url); // http://51js.com

It is obvious that changeurl directly modifies the value of wuyouuser. url, so the http://51js.com can be output later

If you don't understand this section, don't worry about programming. A lot of things can only be said, and I don't have the ability to speak clearly. As long as you write more code in the future, if you use a multi-purpose class, you will naturally understand this. You can also look at the jsvm code. Almost every class in it uses the attributes and methods when the class is used as an object.

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.