JavaScript Learning Summary: Two ways of JS inheritance

Source: Internet
Author: User
Tags constructor copy implement inheritance variables version variable domain

Article Introduction: The summary is to use the call method of the object posing mechanism to crawl the attributes of the parent class, while the member method should be written into the prototype domain shared by all object instances to prevent duplicate method copy creation. The subclass then inherits the parent class prototype domain to catch all of the methods removed. If you want to completely clarify the relationship between these call chain, recommend that you pay more attention to JS prototype Constru

Always want to do some of JavaScript again, just recently wrote a small JS UI library, summed up the inheritance of JS, the network also saw some predecessors in the blog summary, sensory analysis is not particularly comprehensive. Here is just to share their learning experience, I hope to learn from JavaScript to help you.

JavaScript itself evolved from the syntax of the Perl language, which is essentially a scripting language, as the version of the update gradually added to the object-oriented simulation. I think JS's object-oriented simulation is generally good, because we can not blindly follow any idea, not purely for OOP and OOP, we need to seize the benefits of the object in the end is what? For these advantages to OOP, is the most sensible choice, so that JS did a good job.

JS inheritance in a lot of books carefully divided into a number of types and implementation of the way, is basically two: object posing, prototype mode. Each of these two ways has advantages and disadvantages, here I first enumerate, and then from the bottom of the analysis of the difference:

(i) object posing as

 
  
  


When constructing object B, calling temp is equivalent to starting a constructor, noting that the this object in the context environment here is an instance of B, so when the a constructor script is executed, all a variables and methods are assigned to the object referred to in this, that is, the instance of B. This achieves the purpose of B inheriting the attribute method of a. The temporary reference to temp is then removed to prevent reference changes to a class object (note that is not an instance object) in B, because changing the temp directly results in a change in the structure of Class A (attention is not object of Class A).

We have seen that, in the JS version update process, in order to facilitate the implementation of this context of this switch to achieve inheritance or more broadly, add the call and apply functions. They are the same principle, just a different version of the argument (a variable arbitrary parameter, one must pass in the array as a parameter set). In this case, call is used as an example to explain how the object that is implemented with call is impersonating inheritance.

 
  
  
  1. function Rect (width, height) {
  2. this.width = width;
  3. this.height = height;
  4. This.area = function () {return this.width*this.height;};
  5. function myrect (width, height, name) {
  6. rect. Call (This,width,height);
  7. this.name = name;
  8. this.show = function () {
  9. alert (this.name+ "with area:" +this.area ());
  • }

  • about the call method, official explanation: One method of invoking an object, replacing the current object with another object.
    Call (Thisob,arg1, arg2 ...)

    This is also an object pseudo inheritance, but what happens when the call method is invoked is also the substitution of this context variable this, in the Myrect function body, this must be an instance of the class Myrect object. However, using this as a context variable invokes the name Rect method, which is the constructor of the class rect. So the assignment property and method of this call at this time is actually rect to a Myrect object. So although call and apply are not new methods just for inheritance, they can be used to simulate inheritance. The

    object is one such thing as inheritance, and it can implement multiple inheritance, as long as it repeats the process of assigning this set of values. But at present, the real large-scale use is not much, why? Because it has an obvious performance flaw, this is about the concept of OO, we say that objects are members + member methods of the collection, when constructing object instances, these instances only need to have their own member variables can be, the member method is only a section of the operation of the executable text area, This area does not need to be replicated for each instance, and all instances can be shared. Now back to JS. Using object impersonation as an inheritance, all member methods are created for this, which means that all instances will have a copy of the member method, which is an extreme waste of memory resources. Other flaws such as the object posing as the prototype domain variables and methods do not mention, I think the previous fatal flaw is enough. However, we still need to understand it, especially the parent class of the attributes and methods are inherited from the principle of understanding JS inheritance is very important.

    (ii) prototype way
    the second way of inheriting is the archetypal way, the so-called archetype method of inheritance, which is the use of prototype or in some way to cover the prototype, so as to achieve the purpose of property method replication. There are many ways to implement it, and there may be a little difference between the different frames, but if we hold the principle, there will be no place for us to understand. Look at an example (an implementation):

       
        
        


    The key is to assign the last sentence Student prototype property to the object constructed by the person class, where the author explains how the properties and methods of the parent class are copy to the subclass. When a JS object reads a property of an object, it always first looks at the list of properties of its own domain, and if it returns otherwise reads the prototype domain (all the properties and methods of the prototype domain of the class that constructs the object), and returns if found. Because the prototype can point to other objects, the JS interpreter recursively looks for the prototype field to point to the prototype field of the object, until prototype is itself, the lookup becomes a loop, stops, and at this point it is undefined.

    Thus, the effect of the last sentence is to connect all the properties and methods of the parent class to the prototype domain of the subclass, which inherits all the properties and methods of the parent class, including name, Saygoodbye, and SayHello. Instead of seeing the last sentence as an assignment, it's better to understand it as a point relationship. The defects of this prototype inheritance are also quite obvious, is that the constructor of the parent class cannot take arguments when inheriting, because the modification of the prototype domain of the child class is not possible until the subclass object is declared, and it is impossible to initialize the parent class property with the arguments of the subclass constructor, as follows:

     
      
      

    Two methods of inheritance have been finished, if we understand the two ways of how the parent class to "crawl" the attributes and methods, you can freely combine their pros and cons, to achieve a truly reasonable JS inheritance. Here is an integrated approach to personal summary:

     
      
      

    The summary is to use the call method of the object posing mechanism to crawl the attributes of the parent class, while the member method should be written into the prototype domain shared by all object instances to prevent duplicate method copy creation. The subclass then inherits the parent class prototype domain to catch all of the methods removed. If you want to completely clarify the relationship between these call chain, recommend that you pay more attention to the prototype in JS constructor and objects of the constructor attribute, here is not to say more.



    Related Article

    Cloud Intelligence Leading the Digital Future

    Alibaba Cloud ACtivate Online Conference, Nov. 20th & 21st, 2019 (UTC+08)

    Register Now >

    Starter Package

    SSD Cloud server and data transfer for only $2.50 a month

    Get Started >

    Alibaba Cloud Free Trial

    Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

    Learn more >

    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.