Old fish talking about JavaScript Object-Oriented Programming

Source: Internet
Author: User
Tags cdata

The exclamation is to ease the serious atmosphere and bring out the topic to be discussed today, "javascript object-oriented programming". Next, we will focus on several major object-oriented keywords: encapsulation, inheritance, and polymorphism, expand.
Encapsulation: In the mode in which objects are created in Javascript, I personally think that the closure is actually an encapsulation. So first, let's briefly introduce the closure and take a look at the following example: CopyCode The Code is as follows: <SCRIPT type = "text/JavaScript"> // <! [CDATA [
Function myinfo (){
VaR name = "old fish", age = 27;
VaR myinfo = "my name is" + name + "I am" + age + "years old ";
Function showinfo (){
Alert (myinfo );
}
Return showinfo;
}
VaR oldfish = myinfo ();
Oldfish ();
//]> </SCRIPT>

Are you familiar with it? That's right. This is actually a simple closure application. A simple explanation: the variables defined in the above function myinfo are accessible in its embedded function showinfo (this is easy to understand ), however, when we assign a value to the oldfish variable for the returned reference of this nested function, showinfo is called in the external body of myinfo function, but can also access the variables defined in the function body. Oh yeah!
To sum up the principle of the closure, the function runs in defining their scopes rather than calling their scopes. Actually, returning an embedded function is also the most common method to create a closure!
If we think the above explanation is too abstract, let's reinvent the above functions together to see if there are clear layers:Copy codeThe Code is as follows: <SCRIPT type = "text/JavaScript"> // <! [CDATA [
VaR ioldfish = function (name, age ){
VaR name = Name, age = age;
VaR myinfo = "my name is" + name + "I am" + age + "years old ";
Return {
Showinfo: function (){
Alert (myinfo );
}
}
}
Ioldfish ("old fish", 27). showinfo ();
//]> </SCRIPT>

In the preceding example, the encoding style is common in ext Yui, Which is distinct between public and private. Through the closure, we can easily hide things that do not want to be directly accessed by external entities. You need to access the variables defined in the function, it can only be accessed through a specific method. direct access from the outside is not accessible, and the writing is quite tiring. After a lap, it finally turns back and encapsulates it, it's not just hiding what you don't want to be seen by others! Haha ......
In the previous example, if it is converted to the JQ style, it should be written in the following example. This encapsulation mode belongs to the portal wide-open mode, the variables defined in them can be accessed externally (in the following example, if you instantiate an object first, and then the name or age attribute of the object accessed externally by the function can be read) of course, in this mode, we can set some "Hidden Rules" so that team developers can understand which variables are private. Generally, we manually underline "_" before private variables and methods "_", identify alert signals! To implement "encapsulation "! Copy code The Code is as follows: <SCRIPT type = "text/JavaScript"> // <! [CDATA [
VaR ioldfish = function (name, age ){
Return ioldfish. func. INIT (name, age );
};
Ioldfish. func = ioldfish. Prototype = {
Init: function (name, age ){
This. Name = Name;
This. Age = age;
Return this;
},
Showinfo: function (){
VaR info = "my name is" + this. Name + "I am" + this. Age + "years old ";
Alert (Info );
}
};
Ioldfish. func. init. Prototype = ioldfish. func;
Ioldfish ("old fish", 27). showinfo ();
// Var oldfish = new ioldfish ("old fish", 27 );
// Alert (oldfish. Name );
//]> </SCRIPT>

someone may ask, which mode is better? What should I do? Both methods have advantages and disadvantages! In short, there must be something that cannot be directly accessed by external objects. Use closures to encapsulate it ." The four words must be profound and can be understood in practice!
inheritance: when we mention this, we should add another one: a disadvantage in closure encapsulation is not conducive to subclass derivation. Therefore, closure is risky and encapsulation should be cautious! For the sake of intuition, the method for creating objects in the following example adopts the "wide-open portal" mode.
in Javascript, inheritance is generally divided into three methods: "class inheritance", "prototype inheritance", and "meta-classes ". The following describes the principles of the three types of inheritance methods.
. class inheritance: this is a common inheritance method in mainstream frameworks. See the following example: copy Code the code is as follows:

the above subclass fish does not define the getname method, but ioldfish, An Instance Object of the subclass fish, still calls this method because the subclass fish inherits the getname method defined in the superclass name. Here, the prototype of the sub-class fish refers to an instance of the super class. Although the getname method is not affirmed in the sub-class fish, according to the prototype chain principle, the method will be directed to the higher-level object indicated by prototype to check whether this method exists. If this method is not found, the original prototype object will be searched all the time. This is actually the principle of inheritance. Fish. prototype. constructor = fish; because the prototype of the default subclass should point to itself, but the prototype previously points to the superclass instance object, it should be set back here. Of course, the relevant code can be organized here through a function to play the role of disguising extend. I will not elaborate on it here. I can follow my next blog post ......
B. Prototype inheritance, which is superior to class inheritance in terms of memory performance. copy Code the code is as follows:

Obviously, the core of prototype inheritance is the clone function, which is also the principle of prototype chain. The difference is that it directly clones the superclass, so that the subclass inherits all attributes and methods of the superclass. in particular, this type of inheritance does not need to create constructor. Instead, you only need to create an object Word variable, define the corresponding attributes and methods, and then use dots in the subclass ". to reference attributes and methods.
C. meta-classes: encapsulate some commonly used methods with greater versatility in a single function, and then assign them to the classes that need these methods through the following function. you can also selectively transfer required methods for different classes. Copy code The Code is as follows: <SCRIPT type = "text/JavaScript"> // <! [CDATA [
Function agument (receveclass, giveclass ){
If (arguments [2]) {
VaR Len = arguments. length;
For (I = 2; I <Len; I ++ ){
Receveclass. Prototype [arguments [I] = giveclass. Prototype [arguments [I];
}
}
Else {
For (method in giveclass. Prototype ){
If (! Receveclass. Prototype [Method]) {
Receveclass. Prototype [Method] = giveclass. Prototype [Method];
}
}
}
};
VaR name = function (){};
Name. Prototype = {
Saylike: function (){
Alert ("I like oldfish ");
},
Saylove: function (){
Alert ("I love oldfish ");
}
}
VaR fish = function (){};
VaR ioldfish = new fish ();
Agument (fish, name, "saylove ");
Ioldfish. saylove ();
Ioldfish. saylike ();
//]> </SCRIPT>

Polymorphism: I personally think This is abstract and difficult to describe, so I will briefly describe it from two aspects: heavy load and coverage.
Overload: In the above example, the agument function initially includes two parameters, but in subsequent calls, agument (fish, name, "saylove") can also include any number of parameters, javascript Overloading is implemented by the user in the function by operating the arguments attribute.
Overwrite: This is very simple, that is, if the method defined in the subclass has the same name as the method inherited from the superclass, it will overwrite this method (here it is not a method that covers the superclass, pay attention to it ), this is not cumbersome!
Finally, let's focus on this and the execution context. In the preceding encapsulation example, this indicates the instantiation object of the class where this is located, but it is not the same. For example, for the event processing Code defined by the HTML attribute, see the following code:Copy codeThe Code is as follows: <SCRIPT type = "text/JavaScript"> // <! [CDATA [
VaR name = function (name ){
This. Name = Name;
This. getname = function (){
Alert (this. Name );
}
};
VaR ioldfish = new name ("old fish "),
BTN = Document. getelementbyid ('btn ');
BTN. onclick = ioldfish. getname;
// BTN. onclick = function () {ioldfish. getname. Call (ioldfish )};
//]> </SCRIPT>

After the button is clicked in the previous example, the attributes of the Instance Object are not displayed in the pop-up box. This is because the execution context of this has changed. The current context of this object should be the HTML Tag of input, however, the tag does not have the getname attribute. Therefore, the attribute value cannot be output! From this example, we can easily see that the execution context is determined during execution and can be changed at any time.
Of course, you can remove the code I commented out above and change the execution context of this through call to get the getname method. The apply method can also change the execution context, but a more elegant implementation method BIND is found in the prototype framework. Let's take a look at the implementation of this method. We have to lament the greatness of our predecessors ......Copy codeThe Code is as follows: function. Prototype. Bind = function (OBJ ){
VaR method = This,
Temp = function (){
Return method. Apply (OBJ, arguments );
};
}

I believe that if you can understand it, you can rely on these knowledge points to write a simple script framework. I believe that you will be able to master it in the near future! If you don't understand it, you don't have to worry about it. The object orientation is a little abstract. You should be OK to practice more. Come on ......
Write this article first. NextArticleWe can discuss with you the design mode of JavaScript.

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.