JavaScript design pattern reading Essays (i)--javascript object-oriented

Source: Internet
Author: User

Object-oriented in JavaScript is essentially an abstraction of a requirement into an object that contains properties and methods that can be used to describe or manipulate a class of objects called classes.

Thethree elements of object-oriented in JAV A are: encapsulation, inheritance, polymorphism, which can also be implemented without a keyword or method such as class or extend before ES6.

Create a class

Creating a class pass before ES6 can be done by declaring a function to hold it in a variable, by adding properties and methods to this, or by adding properties and methods to the class's prototype.

You can see that when you create a book class in the console, the book's instantiation object book contains two attribute IDs and name, and its stealth prototype __proto__ contains a constructor attribute, which points to the prototype object.

If you add a method or property to the book's prototype: like book. Prototype.display = function () {...} each instantiated object is inherited to this method through the prototype chain, but this is not her own method and needs to be accessed through prototype.

Now that ES6 introduces class to create classes, the constructor method is the default method for the class, which is called automatically when an object instance is generated from the new command.

1 class Book {2  constructor (ID, name) {3this     . id = ID; 4     this. Name = name; 5   }6 }

Packaging

Using the function scope of JavaScript, you can create private variables and private methods for a class, creating common properties and common methods for a class with this. The code is the essence of the JavaScript package I understand.

1 varBook =function(id,name) {2   //The security check determines whether the current object is present during execution.3   //avoid creating global objects by mistake4   if( This instanceofBook ) {5      This. Name =name;6}Else {7     return NewBook (id,name);8   }9   //Private PropertiesTen   varnum = 1; One   //Private Methods A   functionCheckid () { -     returnnum + ' x ' +ID; -   } the   //public properties and public methods -    This. ID =ID; -    This. Copy =function () {} -   //Privileged Methods +    This. SetName =function(name) {} -    This. GetName =function() { +     //You can access public methods and properties, or you can access private methods and properties when you create an object A   } at   //Constructors -    This. SetName =function(name) { -     //Initialize the instance object with the privileged method when the object is created -   } -   //Closed Package -   returnCheckid; in}

Inherited

Inheritance is the encapsulation of existing objects, from which private properties, public properties, and so on, are different for each property and method feature. There are two types of methods that can be inherited, one in the constructor, one for the properties and methods when the object is instantiated, and one in the prototype object of the class, which can be shared by all instantiated objects.

Class-Type Inheritance:

Class inheritance can be understood as the ability to assign the strength of the parent class to the prototype of the subclass, and to implement the inheritance through the prototype chain.

 1  function   superclass () { 2  this . Books = [' Parent book '  

In this way, newly created objects can access not only properties and methods on the parent prototype, but also properties and methods assigned to the parent class constructor, and the prototype of the subclass can also access methods on the parent class prototype.

The disadvantage is that if an instantiated object modifies the books property, all instantiated object books values will be contaminated.

Constructor Inheritance:

constructor-style inheritance is a good solution to the problems exposed in class-type inheritance. The essence of it is to use the call () function

functionSuperclass (ID) { This. Books = [' Super '];  This. ID =ID;}functionSubclass (ID) {Superclass.call ( This, id);}varInstance1 =NewSubclass (10);varInstance2 =NewSubclass (11); Instance1.books.push (' Sub '); Console.log (instance1.books)//[' Super ', ' Sub ']Console.log (Instance2.books)//[' Super ', ' Sub ']Console.log (instance1.id)//TenConsole.log (instance2.id)// One

It can be seen that by calling () This function changes the environment of the function, invoking the parent class in the subclass executes the variable in the subclass into the parent class. This type of inheritance does not involve prototypes, so the method of the parent prototype cannot be inherited by the quilt class.

Combination Inheritance:

Combinatorial inheritance is the combination of primitive inheritance in class inheritance and the two-point inheritance of constructor-type inheritance in the context of a subclass constructor that executes a parent class once.

functionSuperclass (ID) { This. Books = [' Super '];  This. ID =ID;} SuperClass.prototype.getId=function() {Console.log ( This. ID);}functionSubclass (Id,name) {//inheriting the parent class ID attribute in the constructorSuperclass.call ( This, id);  This. Name =name;}//class-Inheriting prototypes inherit from the parent classSubclass.prototype =Newsuperclass ();//new sub-class prototyping methodSubClass.prototype.getName =function() {Console.log ( This. name);}varInstance1 =NewSubclass, ' Sub1 ');varInstance2 =NewSubclass (One, ' sub2 ')); Instance1.books.push (' Sub1-1 '); Console.log (instance1.books)//[' super ', ' sub1-1 ']Console.log (Instance2.books)//[' super ']Instance1.getname ()//TenInstance1.gettime ()//Sub2

Parasitic combination inheritance:

functionInheritobject (o) {//Transition Objects  functionF () {}//prototype InheritanceF.prototype =o; //returns a prototype that inherits an instance of the parent class object  return NewF ();}functionInheritprototype (subclass, superclass) {//copy a copy of the prototype of a parent class saved in a variable  varp =Inheritobject (Superclass.prototype); //Fix the subclass constructor property is modified because the subclass prototype is overriddenP.constructor =Subclass; //set up a prototype for a subclassSubclass.prototype =p;}functionSuperclass (ID) { This. Books = [' Super '];  This. ID =ID;} SuperClass.prototype.getId=function() {Console.log ( This. ID);}functionSubclass (Id,name) {//inheriting the parent class ID attribute in the constructorSuperclass.call ( This, id);  This. Name =name;} Inheritprototype (subclass, superclass) SubClass.prototype.getName=function() {Console.log ( This. name);}varInstance1 =NewSubclass, ' Sub12 ');varInstance2 =NewSubclass (, ' sub13 ');

The biggest change is that the prototype of the subclass is given a reference to the prototype of the parent class, when the subclass wants to add a prototype method that must be added through prototype.

The above is ES6 before, in the use of JavaScript inheritance most of the methods used, then in ES6, we can use the keyword concise and clear to achieve the purpose of inheritance

  Constructor (x, y, color) {3     super (x, y);//Call the parent class's constructor (x, y) 4     this.color =  } 6    ToString () {8      }10}  

The constructor of the parent class must be called using super () in the constructor of the subclass, because the subclass's own this object must first be constructed from the parent class's constructor, get the same instance properties and methods as the parent class, and then process it, plus the subclass's own instance properties and methods. If you do not call the Super method, the subclass will not get the This object. Therefore, only after the super is called, the subclass's this can be used normally.

Polymorphic

Polymorphism can be understood as, when invoking a method, the number of passed parameters, the type is not the same, there are many ways to implement. It can be said that depending on the interface, different results are rendered.

For ES6 before the implementation of inheritance, polymorphism, encapsulation principle, mainly around the prototype, prototype chain call to achieve, although the current ES6 can be very good to achieve these soul play, including the current trend of the typesscript is to put JS into the strong type of language circle, but original aim, understand the principle, In order to better use.                          ,         &NB Sp                          ,         &NB Sp                          ,         &NB Sp                          ,         &NB Sp                          ,         &NB Sp                          ,         &NB Sp                          ,         &NB Sp &nbSp                          ,         &NB Sp                          ,         &NB Sp                          ,         &NB Sp                          ,         &NB Sp                          ,         &NB Sp                          ,         &NB Sp                          ,         &NB Sp                                 &NBsp                          ,         &NB Sp                          ,         &NB Sp                          ,         &NB Sp                          ,         &NB Sp                          ,         &NB Sp                          ,         &NB Sp                          ,         &NB Sp                                 &nbsp                          ,         &NB Sp                          ,         &NB Sp                          ,         &NB Sp                          ,         &NB Sp                          ,         &NB Sp                          ,         &NB Sp                          ,         &NB Sp                                                         ,         &NB Sp                          ,         &NB Sp                          ,         &NB Sp                          ,         &NB Sp                          ,         &NB Sp                          ,         &NB Sp                          ,         &NB Sp                                                            ,         &N Bsp                          ,         &NB Sp               

JavaScript design pattern reading Essays (i)--javascript object-oriented

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.