Implementation of inheritance in JavaScript (1)

Source: Internet
Author: User
Tags ming

Introduction: Learning the object-oriented language (Java, C + +) of children's shoes are aware of the concept of object-oriented, and certainly know the characteristics of object-oriented language: encapsulation, inheritance and polymorphism, but JavaScript is not object-oriented, but based on the object , these concepts cannot be applied directly to the object mechanism of JavaScript, and this section focuses on how JavaScript developers can achieve the inheritance characteristics of object-oriented languages.

1. Overview of the class?

  class: A class is the basis for an object-oriented language. class is like a model , for example, an animal is a class is vague and not specific, has a lot of characteristics, but we do not know that it will fly, climb, swim.

  object: Then the object is like a concrete embodiment of the class, such as the dog this animal is the real existence, all the characteristics are fixed, will run, will bark and so on.

  Object-oriented : object-oriented It is more emphasized that the behavior of data and manipulation data is interrelated , the implementation is to encapsulate the data and the associated behavior as a class , based on the class to complete the development of object-oriented language.

  Example: A character that represents a word or phrase is often referred to as a string . But what we often care about is not the data itself, but the operations associated with the data. Therefore, the data (characters) and behavior (calculation length, add and subtract data, etc.) are encapsulated into a uniform string class , and all strings are an instance of the string class.

2. What is inheritance? What are the benefits of inheritance?

In real life we often use the word inheritance, such as: birds inherit the characteristics of mother. Can inherit the mother's attributes (feathers, limbs, etc.), can also inherit the mother's behavior (tweet, fly, etc.), the program's inheritance and its similar.

  inheritance: subclasses inherit the properties and methods of the parent class without overriding the parent class properties and methods, and they can be called directly .

  benefit: improved code reusability.

Implementations of inheritance in 3.JavaScript

  In other languages (Java), subclasses inherit the parent class to get just one copy of the parent class, and the inheritance of the class is essentially the replication of the class . But there are only objects in JavaScript , and there is no function of copying between the objects. So how do JavaScript developers implement object-oriented language inheritance behavior.

  1> Constructor Inheritance

The subclass inherits from the parent class through the Call/apply method in the child class.

        //defines a constructor named person, and the constructor binds only the property name        functionPerson (name) { This. Name =name This. GetName =function() {                return  This. Name; }        }        //define the constructor bar (), define the property name and label        functionStudent (name, hobby) {//change the point of this by call, inherit the attribute in person name and Method GetName ()Person.call ( This, name) This. Hobby =Hobby;  This. Gethobby =function () {                return  This. Hobby}} varA =NewStudent ("Xiao Ming", "BasketBall");        Console.log (A.getname ()); Console.log (A.gethobby ());

The previous example of a neutron class student inherits the Name property and the GetName () method of the parent class person through Person.call (this.name), and we can call the Name property and student directly in the instance of GetName () method.

  Analysis:<1>person the GetName () method behaves the same in all instances, and each instantiation of an object defines a GetName () method that behaves the same, but we want all instances to share the same getname () method, All GetName () The best way is defined on the prototype.

  Disadvantages:

    <1>: Each instance has the same behavior as the GetName () method, which causes a waste of memory.

    <2> cannot be reused for code, Best Practices GetName () method all instances share the same one.

<3> causes inheritance of excess attributes of the parent class

  2> prototype prototype mode inheritance

Function has the prototype property, in the design of the constructor, we will not need to share the properties and methods, defined in the constructor, the need to share the properties and methods, are placed in the prototype;

        //define the unshared Name property in the person function        functionPerson (name) { This. Name =name}//define the GetName method that needs to be shared on the prototypePerson.prototype.getName =function(){            return  This. Name}//define the constructor student (), define the property name and label        functionStudent (name, hobby) {//change the point of this by call, inheriting the attribute in person namePerson.call ( This, name) This. Hobby =Hobby; }        //student inherits the method in personStudent.prototype =NewPerson ()//fixed a pointer to the constructor of studentStudent.prototype.constructor =Student//Student method for defining GethobbyStudent.prototype.getHobby =function() {            return  This. Hobby}varStu =NewStudent ("Xiao Ming", "BasketBall");        Console.log (Stu.getname ());        Console.log (Stu.gethobby ()); 

  Analysis:

 1>. Student.prototype = new Person () in the Code, The value of the person instance assigned to Student.prototype,student.prototype was deleted. 
2>. What does Student.prototype.constructor = Student do? each prototype object has a constructor property, if there is no student.prototype = new Person (),
Student.prototype constructor is point to Student, after performing this line constructor point to person, more importantly, Each instance has a constructor property , which calls the constructor property in prototype by default.
after calling Student.prototype = new person (), Stu.constructor also points to person.
        Console.log (Student.prototype.constructor = = person)   //  true        Console.log ( Stu.constructor = = = person)                 //  true        console.log (stu.constructor = = = Student.prototype.constructor)  //true

This leads to confusion in the inheritance chain, because Stu is an instance of Student, not an instance of person, so we need to manually fix Student.prototype.constructor = Student.

3>: In the example above for student.prototype = new Person (), we can use Student.prototype = person.prototype substitution , There is no need to execute the person function (to improve performance) compared to the first, and there is no need to create an instance (saving memory) while shortening the invocation of the prototype chain.

    Cons: causes Student.prototype and Person.prototype to point to the same object reference , modifying either one of the other to be affected. For example: Student.prototype.constructor = Student will cause Person.prototype.constructor is also Student.

Console.log (Person.prototype.constructor = = = Student)   //  true

  3>prototype Mode Improvements

Since student.prototype = new person () and Student.prototype = Person.prototype have drawbacks in two ways, we use empty objects as mediations for optimization.

        /*1>f is an empty function for performance loss and memory waste negligible 2> does not cause child.prototype and parent.prototype to point to the same reference*/        functionExtend (parent, child) {functionF () {} F.prototype=Parent.prototype Child.prototype=NewF () child.prototype.constructor=Child }//define the unshared Name property in the person function        functionPerson (name) { This. Name =name}//the GetName method that will need to be sharedPerson.prototype.getName =function(){            return  This. Name}//define constructors Student (), define properties name and hobby        functionStudent (name, hobby) {//change the point of this by call, inherit the attribute in person name and Method GetName ()Person.call ( This, name) This. Hobby =Hobby; } Extend (person, Student) Student.prototype.getHobby=function() {            return  This. Hobby}varStu =NewStudent ("Xiao Ming", "BasketBall");             Console.log (Stu.getname ()); //Xiao MingConsole.log (Stu.gethobby ());//BasketballConsole.log (Student.prototype.constructor)//StudentConsole.log (Person.prototype.constructor)// Person

  Analysis:

1> we have encapsulated the Extend method in the above example, we use the empty constructor F as the intermediary in extend to avoid the shortcomings in the previous implementation.

     1>f is an empty function for performance loss and memory waste negligible    2> does not cause child.prototype and parent.prototype to point to the same reference

2> for our own encapsulation of the Extend method, we can actually use the object.create (proto,properties) provided in the ES5 to replace, the effect is the same.

Student.prototype = Object.create (Person.prototype)

    Note: The internal implementation of the Object.create () method is similar to our own encapsulated extend method.

  

Implementation of inheritance in JavaScript (1)

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.