Old fish talking about javascript Object-Oriented Programming

Source: Internet
Author: User

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:
Copy codeThe 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 codeThe 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>

Some 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 the closure encapsulation is not conducive to subclass derivation. Therefore, the closure is risky and the 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.
A. class inheritance: this is A common inheritance method in mainstream frameworks. See the following example:
Copy codeThe Code is as follows: <script type = "text/javascript"> // <! [CDATA [
Var Name = function (name ){
This. name = name;
};
Name. prototype. getName = function (){
Alert (this. name );
};
Var Fish = function (name, age ){
Name. call (this, name );
This. age = age;
};
Fish. prototype = new Name ();
Fish. prototype. constructor = Fish;
Fish. prototype. showInfo = function (){
Alert (this. age );
}
Var ioldFish = new Fish ("old Fish", 27 );
IoldFish. getName ();
//]> </Script>

The above subclass Fish does not define the getName method, but the ioldFish 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 codeThe Code is as follows: <script type = "text/javascript"> // <! [CDATA [
Function clone (object ){
Var F = function (){};
F. prototype = object;
Return new F ();
};
Var Name = {
Name: "who's name ",
ShowInfo: function (){
Alert (this. name );
}
};
Var Fish = clone (Name );
// Fish. name = "old Fish ";
Fish. showInfo ();
//]> </Script>

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 codeThe 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 ......
I will write this article first. In the next article, I will discuss with you about the javascript design mode, so stay tuned.

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.