JavaScript Series----Object-oriented JavaScript

Source: Internet
Author: User

1. Object-oriented Programming 1.1. What is object-oriented programming

Object-oriented programming: that is, the ability to complete a part of the function of a separate code together to form a class.


For example:

There is a gun, a lot of guns, rifles, machine guns, sniper guns ..... But anyway, these are the concepts of guns, and if this abstraction is stripped out, it is what we often call "class." So what are the characteristics of a gun? Weinig size, model, length, bullet type, number of bullets to load, muzzle radius ... ok! All of this is for the sake of the gun, the abstraction of these, the composition of the "Gun class" property.  What can a gun do? Aim, Fire,.... These are the functions of the gun-----The abstraction, that is, the method of forming a class.

Therefore, in general, object-oriented programming is to put a program modular, each module carries a part of the function, each module to cooperate to maintain the normal implementation of the program;

The composition of the so-called class consists of no more than three parts: the name of the class (corresponding to the "gun" in the example), the attribute of the class (corresponding to the feature), the method of the class (corresponding to the function).

Just as we describe a person, no matter what, the characteristics of a person and human ability. So, in real life people, in the program can also be abstracted into classes.

1.2. Relationship of class, object, instance
    • Class: is an abstract concept, an abstraction of a class of similar objects.
    • Object: is an instantiation of the class, because the class is an abstract concept, so it must be implemented into the physical body when it is used. Then, the object acts as a vector to accomplish a function.
    • Example: And an object is a concept. Generally speaking, an instance of a class refers to an object of this class.

Give an example to illustrate the relationship between the three:

1.Person is the name of a class, defined by a person, the description of the person is generally the name, age.
var person = function (name, age) {
The Properties of the//person class this. Name = name; this. Age = Age ;}
methods of the//person class = function () { console.log ('hello');}
This is the instantiation of a class, Lisi here is an object of the person class, or it can be said to be an instance of the person class.
var lisi=new person ("Lisi", 18);
1.3. Object-oriented four features
    • encapsulation. The so-called encapsulation is to encapsulate the properties and methods of a class's objects inside the class. The advantage of encapsulation is that the properties and methods between classes and classes are independent of each other and do not interfere with each other.
    • inheritance. The so-called inheritance means that a class can derive from another class. For example, the graph class, can derive the triangle, the square, the circle ....
    • overloaded. overloading means that a method of a class can have the same name (JS does not support overloading). The second part gives an explanation.
    • Polymorphic . polymorphism refers to the method of the parent class, which can be overridden by subclasses. Then, the child class will call the method when it is called a subclass.

Remember: Object-oriented, and all of this is for code reuse.

2. Object-oriented four features in JS in the implementation of 2.1.JS packaging

The encapsulation of the JS class is to encapsulate the properties and methods of the class within the class. If you are simply implementing encapsulation, there are several ways to do it. For example, two of the following

//The first method
varperson =function (name, age) { This. Name =name; This. Age =Age ; This. Greet =function () {Console.log ('Hello'); }}
//second method varperson =function (name, age) { This. Name =name; This. Age =Age ;} Person.prototype.greet=function () {Console.log ('Hello');}

These two methods, although consistent in the use of the effect, but in the first method, each time you new an object to add a function greet----so that the code is not reused. So in the use of time, is generally used in the second way---is called modular creation. So in general we also recommend the second way.

No overloads exist in 2.2.JS

What is overloading? The concept of overloading comes from the strong-type prophecy (c++,java,c#). Let's start by looking at some of the overloads in Java

classperson{//java Language, defines a person class that has overloads of the greet method in that class.  PublicString name;  Public intAge ; Person (String name,intAge ) {         This. name=name;  This. age=Age ; }            Public voidgreet () {System.out.println ("I am" + This. Name); }          Public voidgreet (String message) {System.out.println ("I am" + This. name+ "\ n This is your" +message); }}

The so-called overload is that the same method name is presented multiple times in a class. So when the method is called, how does the compiler differentiate which method to call?

In a strongly typed language, the compiler chooses a function based on the name of the function , and then distinguishes a function based on the type of the parameter and argument, the number of formal parameters and the number of actual arguments, according to the invocation.

So, here's the problem .... Does the interpreter in JS match a function? Ok... The interpreter in JS simply chooses the function based on the name of the function, and the formal parameter of the function is not in the scope of consideration----because the type of the argument cannot be determined at compile time based on the type of the parameter being determined.

Since JS does not support overloading, what happens if a function is rewritten?

var person =function (name, age) { This. Name =name;  This. Age =Age ;  This. Greet =function () {Console.log (' Hello '); }}var Person=function (name, age) { This. Name =name;  This. Age =Age ;} Person.prototype.greet=function () {Console.log (' I've been covered ');} Person.prototype.greet=function (message) {Console.log ("I am the method of rewriting.");} var person=NewPerson ("Zhangsan", 18);p Erson.greet (); //I'm the rewriting method.

According to the above example, it can be seen that no matter what the function's arguments are, as long as the function has the same name, it must be called the last written function of the same name .

Inheritance in 2.3.JS

The source of this concept of inheritance is also object-oriented programming. JS Referral strong type prophecy in the inheritance to do this. So we're going to do it from the inheritance in the strongly typed language---why it's so designed in JS.

2.3.1. Implementation of inheritance in strongly typed languages

In strongly typed languages, assume that there are two classes A, B .... A is the parent class of B. The implementation is as follows:

classa{//  constructor for parent class protected  intx; A (intx) {         This. x=x; }}classBextendsa{ protected  inty; B (intXinty) {//subclass Constructor Super(x);         //In the constructor of the subclass, the first sentence always calls the parent class's constructor, and if it does not, it calls Super () by default, and if there is no parameterless constructor in the parent class, the compilation error occurs.  This. y=y; }

   Public String GetPoint () {
    return  "(" +this.x+ "," +this.y+ ")"; return coordinates (x, y)
}

}

What can we see from the above? is the order in which the object is initialized ... Initializes the parent class first, and initializes the child class.

The order of initialization is: the property of the parent class----The method of the parent class-----The property of the subclass-----The subclass of the class. (We're talking about excluding static data and methods in a class, because static data and methods are initialized when the class is first loaded)

Below we see, JS is how to achieve the same function as above ...

varA =function(x) { This. x =x;}varB =function(x, y) {A.call ( This, x);  Equivalent to the first super () function.  This. y =y;}
//Implementing Inheritancefunctionextend (subclass, superclass) {varPrototype =object.create (superclass); Subclass.prototype=prototype; Subclass.constructor=Subclass;} Extend (B, A); B.prototype.getpoint=function () { return' (' + This. x + ', ' + This. Y + ') ';}

The above two pieces of code, apart from the language features, they implement the function is equivalent. Just the first kind of play is the thought, the second kind of play is the skill.

Ok! below we began to explain the JS designers for the JS language can achieve inheritance efforts.

The 2.3.2.JS language supports the principle of inheritance.

All functions have a prototype property. It is this attribute that helps us do something, first realize that this property is an object.

With a detailed description of the person function we created above, the prototype property of this function is shown below:

This is the intrinsic form of the function at the beginning of the initialization, followed by a sentence

function () {  console.log (' hello ');}

When this sentence is finished, Person.prototype becomes

Person prototype
Constructor Point to Person function
Greet (Greet function)

Explaining so much, it does not seem to explain how inheritance is realized, is it .... Don't panic... Take it easy!!!

Let's take a look at what happens when a function is instantiated.

var lisi=new person ("Lisi", 18); See what happens to the object instantiated by person?

  

Come here, we see it. When creating an object of a constructor with new. This object will have a "__proto__" "built-in property that points to the prototype of the function." ------This is the archetypal object of Lisi's legendary object.

A function has only one prototype (prototype), which assigns the prototype to the __proto__ property of the current object when it is called with new.

When querying the properties of an object, the property of the object itself is queried first, and if it is not found, it is looked up according to the object __proto__ attribute layer.

so it's all about everything, as long as you modify the prototype property of a function, you can implement inheritance.

The following illustration illustrates the process of inheriting B to inherit a.

1. Constructors for Class A, and Class B

var function (x) {  this. x = x;}  var function (x, y) {  a.call (this, x);  // equivalent to the first super () function. this  . y = y;}

2. Modify the prototype of B to make it inherit a

// Implementing Inheritance function extend (subclass, superclass) {  var prototype = object.create (superclass);   = prototype;   =function  () {  returnthis this. y + ') ';}

So, Class B inherits Class A ... The key point is on the prototype property of the function. ----The prototype of the function in the next article.

Multi-state implementation in JS

What is polymorphism?

First of all, it must be stressed that only in the case of the existence of the inheritance can appear polymorphic? What is this for? Because polymorphism refers to a method in which a subclass overrides a parent class: This situation is called polymorphism.

Polymorphism in Java

Public class Test {/** * @param args*/Public StaticvoidMain (string[] args) {//TODO auto-generated Method StubB b=NewB (); String result=B.getpoint ();    SYSTEM.OUT.PRINTLN (result); }}class a{protectedintx; A (intx) {         This. x=x; } public String GetPoint () {return"I am the parent class"; }}class B extends a{protectedinty; B (intXinty)         {super (x);  This. y=y; }
Polymorphic, the parent class overrides the method public String GetPoint () {return"I am a subclass"; }}
Output Result:I'm a sub-category

In JS, the polymorphic condition, also refers to the method of the subclass of the method that overrides the parent class. The above function is so implemented in JS.

varA =function(x) { This. x =x;} A.prototype.getpoint=function () {  return' I am a subclass ';}varB =function(x, y) {A.call ( This, x);//equivalent to the first super () function.    This. y =y;}//Implementing Inheritancefunctionextend (subclass, superclass) {varPrototype =object.create (superclass); Subclass.prototype=prototype; Subclass.constructor=Subclass;} Extend (B, A); B.prototype.getpoint=function () {  return' I am a subclass ';}varb =NewB (1, 2); B.getpoint ();
Output result: I am a subclass

After the above code has been executed, the structure of function B

Class B When instantiated, the Class B object will have an internal attribute pointing to B.prototype. When the instance invokes a function, it queries the object for the existence of the function and, if it does not exist, queries the prototype object, or B.prototype, along the __proto__ property. If this function is found, the query is stopped, otherwise it will follow the object pointed to by the __proto__ property until the highest ancestor has been found.

JavaScript Series----Object-oriented 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.