From shallow to deep understanding of JavaScript class stickers)

Source: Internet
Author: User
Tags abstract definition dot net
Learn more about JavaScript (post)

Large | medium | small [2006/12/05 | by Song] Understand JavaScript classes from shortest to deep (post)
From 51js
I 've been mixing up my script for a while recently and replied to some posts, but I didn't make anything to show it to everyone. I felt a little uneasy, so I wrote something below, it should have been sent in the class encapsulation area. Considering that it is cold, I hope this article can help more friends, so I will put it here.

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> >>>>>>>>>>>>>>>>>>>>>>>>>
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 is intended for attackers who want 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
}

The code above defines 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 attributes. We can set its attributes like this:

Wo. Name = "Weeping hongting ";

It's easy, isn't it? Try to run

Optional values Doc ument. Write (WO. Name );

Let's see if my name is output: Weeping Red Pavilion?

Set the property of Brother bianyuan.

Biyuan. Name = "Biyuan ";

Run

Parameter parameter Doc ument. Write (Biyuan. Name );

The output of "Biyuan" indicates 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 wuyouuser class.

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

After a new user is registered, the number of posts is 0. In the code above, the value of articlecount is set to 0.

Run the following code:

VaR Wo = new wuyouuser ();
Optional values Doc ument. Write (WO. articlecount );

The output is 0, indicating that the articlecount attribute is successfully set to 0 by default.

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> >>>>>>>>>>>>>>>>>>>>>>>>>
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, there are differences between men and women. The Inheritance in programming languages is the same. If a Class A inherits from another class B, Class B is the parent class of Class, 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.

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> >>>>>>>>>>>>>>>>>>>>>>>>>
Postscript

First of all, thank you for your patience. I didn't expect to write so much so that you can write well. Please don't mind.

No matter which language, as long as the class is supported, the class plays a very important role in this language, but not everyone can master it, in order to enable users who have not learned the class and who are still confused about the class, they can clearly understand the concept and usage of the class and make some contributions to the worry-free business, I wrote this article and hope you will like it.

We often talk about JavaScript oo recently, but please remember that JavaScript is not an "Object-Oriented" language and can only be said to be "Object-based" at most ".
The difference between "object-oriented" and "Object-based" makes it difficult for me to find simple and accurate words to describe.
When talking about "Object-Oriented", we may first think of C ++, followed by Java, and then dot net. (We will not discuss other partial languages here)
In fact, C ++ is inferior to Java in implementing the "Object-Oriented" idea, because it still has a lot of "process" things. Java has abandoned multi-inheritance, heavy-load operators, and other "complicated and impractical" things. It focuses its design on interfaces, which not only simplifies the tedious work of programmers, it also makes the entire framework look clearer. The most important thing is that everything in Java exists in the form of classes, without the second form. As for C # In DOTNET later, it looks like a MS brand of Java.

Let's get back to JavaScript.
Javascript is not object-oriented. It does not mean that JavaScript is not actually implemented: Abstract objects, inheritance, overloading, and other object-oriented functions.
It means that the "class" in Javascript is not the concept of "class" in a broad sense. A class is just an abstract definition, while a class defined by "function" in Javascript is essentially an "object "!

In addition, the syntax field of JavaScript is not the whole ie process, but the unit is window object.
The same function definition in different window objects is not the same "class ".

For example:
A.htm defines a Class A function a () {}, and B .htm also defines this class A function (){}

In a.htm, you created an instance: var A = new ();
You get the.htm handle winahandle in B .htm.
Then you get the reference of instance a in a.htm.
VaR A = winahandle.;
You will find that the value of a instanceof A is false, and the value of a instanceof winahandle. A is true.
The original cause is very simple. Class A in B .htm is not equivalent to Class A in a.htm. the syntax of this "class" is limited to the same window object (the same window object does not refer to the same page)

This is obviously against the concept that classes are abstract definitions in a broad sense.

People who know VB should also know that the class in VB (including vbs) after vb4 and before VB. NET is also the case, although it is defined by class.
For example, if you put new A in the session, the next time you extract it from the session, it will not be the original object.
In fact, because the syntax domain is different, the class defined previously cannot be retained until this time. The parser does not know what it is, so it cannot be restored.

By the way, the Inheritance Method in Javascript is prototype inheritance. For details, please refer to this book.

Design Patterns elements of reusable Object Oriented soffware
The Chinese version seems to be called the reusable object-oriented design model.
A good book !!!

JavaScript does not have multiple inheritance. Multi-inheritance is not necessary in object-oriented systems. Although the reusability of multiple inheritance is better, the relationship between classes is too complex.
Generally, we can think of a single thing as a derivative of a certain type of thing. Single inheritance is enough. For other features, we can use interfaces to define it.
There is no interface concept in Javascript, and JavaScript does not need interfaces because it is an interpreted language and does not pre-validate the type of real parameters. As a parameter object, is there a method that is not checked during the loading process until it is run, call if any, and exception if none. You do not need to forcibly declare which interface is inherited to call as a parameter.

But in reality, we still need to design some interfaces, mainly for view consideration, the entire framework is easy to understand!
 

Related Article

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.