JavaScript code Reuse pattern detailed

Source: Internet
Author: User

Code reuse and its principles

Code reuse, as the name implies, is a part of the code that has been written and even reused to build a new program. When we talk about code reuse, the first thing we can think of is inheritance. The principle of code reuse is:

Prioritize the use of object combinations rather than class inheritance

In JS, because there is no class concept, so the concept of the instance is not much meaning, JS object is a simple key-value pair, you can dynamically create and modify them.

But in JS, we can instantiate an object using constructors and the new operator, which is syntactically similar to other programming languages that use classes.

For example:

var trigkit4 = new Person ();

JS seems to be a class when calling the constructor person, but it's actually still a function, which allows us to develop ideas and inheritance patterns that are supposed to be based on classes, which we can call "class inheritance mode."

The traditional inheritance pattern requires class keywords, and we assume that the above class inheritance pattern is a modern inheritance pattern, a pattern that does not need to be considered in a class manner.

Class-style inheritance mode

Look at the following two constructors examples of parent () and child ():

<script type= "Text/javascript" >
function Parent (name) {
this.name = Name | | ' Allen ';
}
Parent.prototype.say = function () {
return this.name;
}
function child (name) {}
Creates an object with the parent constructor and assigns the object to the child prototype for inheritance
function inherit (c,p) {
C.prototype = new P ();//The prototype property should point to an object, not a function
}
Invoking the declared inheritance function
Inherit (child,parent);
</script>

When an object is created using the new Child () statement, it obtains its functionality from the parent () instance through a prototype, such as:

var kid = new Child ();
Kid.say ();
Allen

Prototype chain

To discuss how the prototype chain works in class inheritance mode, we see the object as a block somewhere in memory that contains data and references to other blocks. When you create an object with the new Parent () statement, you create a block to the left of the following figure, which holds the Name property and, if you want to access the Say () method, we can link to the prototype (prototype) attribute of the constructor Parent () __ PROTO__, you can access the right block Parent.prototype.

So what happens when you use var kid = new Child () to create an object? The following figure:

An object created using the new Child () statement is almost empty except for an implicitly linked __proto__. In this case, __proto__ points to an object that was created using the new Parent () statement in the Inherit () function

When Kid.say () is executed, because there is no say () method for the leftmost block object, so he will query the middle block object through the prototype chain, however, there is no say () method in the middle block object, so he queries to the rightmost block object along the prototype chain, and the object has say () Method. Is it over?

This is not the end of the execution here, the Say () method refers to the object created by the This.name,this to the constructor, where it points to the new child (), however, there is no Name attribute in the new Child (), and for this reason, the middle block is queried. And the middle block just has the name attribute, so far, the prototype chain query completed.

Shared prototypes

The rule of this pattern is that reusable members should be transferred to the prototype instead of being placed in this. Therefore, in the purpose of inheritance, anything worthy of inheritance should be implemented in the prototype. Therefore, you can set the prototype of the child object to the same as the prototype of the parent object, as shown in the following example:

function inherit (c,p) {
C.prototype = P.prototype;
}

Child objects share the same prototype as the parent object and can access the Say () method equally. However, the child object does not inherit the Name property

Prototype inheritance

Prototype inheritance is a "modern" class-free inheritance pattern. See the following examples:

<script type= "Text/javascript" >
The object to inherit
var parent = {
Name: "Jack"//There is no semicolon here.
}; New Object
var child = Object (parent); alert (child.name);//jack
</script>

In prototype mode, you do not need to use object literals to create a parent object. As the following code shows, you can use a constructor to create a parent object, in which case the properties of its own properties and the stereotype of the constructor are inherited.

<script type= "Text/javascript" >
Parent constructor
function person () {
THIS.name = "TRIGKIT4";
}
Attributes added to the prototype
Person.prototype.getName = function () {
return this.name;
};
Create a new Person class object
var obj = new person ();
Inherited
var kid = Object (obj);
Alert (Kid.getname ());//TRIGKIT4
</script>

In this mode, you can select a prototype object that inherits only the existing constructors. Object inherits from the object, regardless of how the parent object was created, the following instance:

 <script type= "Text/javascript" 
   //Parent constructor
    function person () {
        this.name = "TRIGKIT4";
   }
   //attributes added to the prototype
    Person.prototype.getName = function () {
         return this.name;
   };
   //Create a new Person class object
    var obj = new person ();
   //Inheriting
    var kid = Object (person.prototype);
    Console.log (typeof kid.getname);//function, as it is in the prototype
    Console.log (typeof Kid.name);//undefined, because only the prototype is an inherited
</script>

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.