Review JavaScript Inheritance Mechanism

Source: Internet
Author: User

In the previous period, the team had a few excellent internal discussions. Here, I will sort out the Inheritance Mechanism shared by masters of the west wind, add some colloquial descriptions as appropriate, and keep them for record filing.

I. Tell a story.

Clarify the relationship between Java and JavaScript as Lei Feng tower. Javascript, formerly known as mocha, was also called livescript. It was created by Brendan eich and is now the chief technology officer of Mozilla.

In 1994, navigator0.9, the first mature web browser in history, was born in Netscape. However, navigator0.9 can only be used for browsing and does not have the ability to interact with visitors. For example, if a user submits a data form and the form is empty, the browser cannot judge it, it can only be submitted directly to the server, and then the null value error is returned, so that users can enter it again, which is obviously inefficient and a waste of resources.

At this time, for Netscape, which is at the forefront of technological innovation, it is necessary to develop a practical client scripting language to deal with these problems, so this task falls into engineer Brendan eich. In his opinion, it is necessary to make the design complex, as long as some simple operations can be done, such as determining whether the user has entered a form.

In 1994, object-oriented programming (Object-Oriented Programming) was booming. c ++ was the most popular language, and Java version 1.0 was about to be released in the next year, brendan eich is inevitably affected. He wants to regard all the data types in Javascript as objects, which is very similar to Java. However, he immediately encountered a problem. Do he need to design an inheritance mechanism?

Ii. Evolution of Inheritance

1. Use the New Keyword to generate an instance

A simple functional scripting language like Form Verification obviously does not require the "inheritance" mechanism. However, if Javascript contains all objects, there is a way to link all objects. Finally, Brendan eich designed "inheritance ". However, he didn't introduce the concept of "class" because Javascript is a complete object-oriented method once "class" is introduced.Programming LanguageIt seems a little too formal, far from the original design, and increases the beginner's entry difficulty.

Refer to C ++ and Java to use the new command to generate an instance:

Write c ++ as follows:

 
Classname * object = new classname (PARAM );

Write Java as follows:

 
Foo = new Foo ();

You can also introduce the new command to JavaScript to generate an instance object from the prototype object. However, if Javascript does not contain a "class", how does one represent a prototype object? Constructor is called when C ++ and Java use the new command ). Brendan eich simplifies the design. In JavaScript, the new command is followed by a constructor instead of a class. For example, there is a prototype called WD constructor that represents a web-developper object.

 
Function WD (skill) {This. Skill = skill ;}

Using the new keyword for this constructor generates an instance of the front-end development object.

 
VaR wd1 = new WD ('html'); console. Log (wd1.skill); // html

The this keyword in the constructor actually represents the newly created instance object.

2. Defects of new objects

Using the new keyword, instance objects generated using constructors cannot share attributes and methods. For example, in the WD object constructor, set a common property skill for an instance object.

 
Function WD (skill) {This. Skill = skill; this. Sex = 'male ';}

Then, two instance objects are generated:

 
VaR wd1 = new WD ('html'); var WD2 = new WD ('css ');

The skill attributes of these two objects are independent. Modifying one of them does not affect the other.

 
Wd1.skill = 'javascript '; console. Log (wd2.skill); // "CSS", not affected by wd1

Each instance object has its own copy of attributes and methods. This is not only unable to achieve data sharing, but also a great waste of resources.

3. Introduce prototype attributes

To share attributes and methods, Brendan eich decided to set a prototype attribute for the constructor. This attribute contains an object (hereinafter referred to as "prototype object"). All the attributes and methods to be shared by instance objects are placed in this object. Those attributes and methods that do not need to be shared are not included in this object, put it in the constructor. Once an instance object is created, the attributes and methods of the prototype object are automatically referenced. That is to say, the attributes and methods of the Instance Object are divided into two types: local and referenced. Taking the WD constructor as an example, we can rewrite it with the prototype attribute:

Function WD (skill) {This. skill = skill;} WD. prototype = {sex: 'male'}; var wd1 = new WD ('html'); var WD2 = new WD ('css '); console. log (wd1.sex); // male console. log (wd2.sex); // male

Now, the sex property is stored in the prototype object, which is shared by two instance objects. If the prototype object is modified, the two instance objects are affected at the same time.

 
WD. Prototype. Sex = 'female '; console. Log (wd1.sex); // female console. Log (wd2.sex); // female

Because all instance objects share the same prototype object, prototype objects seem to be prototype objects, while instance objects seem to "inherit" prototype objects. This is the design idea of the Javascript Inheritance Mechanism.

Iii. How to Implement inheritance of Constructors

Now there is a "MED" object constructor (MED: marketing experience design, marketing experience design)

 
Function med () {This. Aim = "marketing experience design ";}

Still the constructor of the "WD" object,

 
Function WD (skill, sex) {This. Skill = skill; this. Sex = sex ;}

How can we make "WD" inherit "med?

1) apply to constructor implementation

The simplest method is to use the call or apply method to bind the constructor of the parent object to the sub-object, that is, to add a row to the sub-object constructor:

Function WD (skill, sex) {med. apply (this, arguments); this. skill = skill; this. sex = sex;} var wd1 = new WD ("html", "male"); console. log (wd1.aim); // "marketing experience design"

2) prototype mode implementation

We usually use the prototype attribute. If the prototype object of "WD" points to a med instance, all "WD" instances can inherit the Med.

 
WD. Prototype = new med (); // we direct the WD prototype object to a med instance. WD. Prototype. constructor = WD; var wd1 = new WD ("html", "male"); console. Log (wd1.aim); // marketing experience design

This sentence

 
WD. Prototype = new med ();

It is equivalent to completely deleting the original value of the prototype object, and then assigning a new value. So what does the second line mean?

 
WD. Prototype. constructor = WD;

Originally, any prototype object has a constructor attribute pointing to its constructor. That is to say, the constructor attribute of the object WD. Prototype points to WD. We have deleted the original value of this prototype object in the previous step. Therefore, the new prototype object does not have the constructor attribute. We need to manually add it. Otherwise, the subsequent "inheritance chain" will cause problems. This is what the second line means.

Note that this is an important point. It is necessary to follow this point in programming. In the following example, if prototype object is replaced,

 
O. Prototype = {};

Then, the next step is to add the constructor attribute to the new prototype object and direct the attribute back to the original constructor.

 
O. Prototype. constructor = O;

3) directly inherit the implementation from prototype

Because the attributes of the MED object can be directly written to the Med. prototype. Therefore, we can also let WD () skip med () and inherit med. prototype directly. Now, we will first rewrite the med object:

 
Function med () {} med. Prototype. Skill = "med ";

Next, point the WD prototype object to the med prototype object, and the inheritance is completed.

 
WD. prototype = med. prototype; WD. prototype. constructor = WD; var wd1 = new WD ("html", "male"); console. log (wd1.skill); // med

Compared with the previous method, this method has the advantage of high efficiency (no execution or creation of MED instances) and saves memory. The disadvantage is that WD. Prototype And med. Prototype point to the same object. Any modifications to WD. prototype will be reflected in med. prototype. Therefore, the above sectionCodeActually there is a problem. See the second line.

 
WD. Prototype. constructor = WD;

This statement actually removes the constructor attribute of the MED. Prototype object!

 
Console. Log (Med. Prototype. constructor); // WD

4) using an empty object as an intermediary

Because prototype is inherited directly, an empty object can be used as an intermediary.

 
VaR F = function () {}; F. Prototype = med. Prototype; WD. Prototype = new F (); WD. Prototype. constructor = WD;

F is a null object, so it hardly occupies memory. In this case, modifying the prototype object of WD does not affect the prototype object of med.

 
Console. Log (Med. Prototype. constructor); // med

5) encapsulate functions in prototype mode

We encapsulate the above method into a function for ease of use.

 
Function extend (child, parent) {var F = function () {}; F. prototype = parent. prototype; child. prototype = new F (); child. prototype. constructor = Child ;}

The method is as follows:

 
Extend (WD, Med); var wd1 = new WD ("html", "male"); console. Log (wd1.aim); // marketing experience design

This extend function is how the Yui library implements inheritance.

6) Copy inheritance implementation

The prototype method is used to implement inheritance. In fact, since the Sub-object will have the attributes and methods of the parent object, we can directly use the "copy" method to achieve the effect. Simply put, if we copy all the attributes and methods of the parent object into the sub-object, can we still implement inheritance? First, put all the unchanged attributes of med on its prototype object.

Function med () {} med. Prototype. Aim = "marketing experience design ";

Then, write a function to copy the attributes.

 
Function extendcopy (child, parent) {var P = parent. prototype; var c = child. prototype; For (var I in P) {C [I] = P [I] ;}}

This function is used to copy the attributes of the prototype object of the parent object to the prototype object of the Child object. Write as follows:

 
Extendcopy (WD, Med); var wd1 = new WD ("html", "male"); console. Log (wd1.aim); // marketing experience design

Iv. How to Implement inheritance of non-Constructor

For example, there is now an object called "med"-marketing experience design.

 
VaR med = {Aim: 'marketing experience Design '}

Another object is called "front-end development ".

 
VaR WD = {skill: 'html '}

How can we let "front-end development" inherit "marketing experience design", that is, how can I generate a "marketing experience design front-end development" object? Note that these two objects are common objects. They are not constructor and cannot be used to implement "inheritance ".

1. Object () method

Douglas crockford, inventor of JSON format, proposed an object () function to achieve this.

Function object (o) {function f () {} f. Prototype = O; return new F ();}

This object () function is actually only used to direct the prototype attribute of the Child object to the parent object so that the child object can be connected with the parent object. When used, the first step is to generate sub-Objects Based on the parent object:

 
VaR WD = Object (MED );

Then, add the attributes of the sub-object:

 
WD. Skill = 'html ';

At this time, the sub-object has inherited the attributes of the parent object.

 
Console. Log (WD. Aim); // marketing experience design

2. Shallow copy

In addition to the prototype chain, there is another idea: copying all attributes of the parent object to the sub-object can also realize inheritance. The following function is used for copying:

 
Function lightcopy (p) {var C ={}; for (var I in P) {C [I] = P [I] ;}// C. uber = P; return C ;}

Write as follows:

 
VaR WD = lightcopy (MED); WD. Aim = 'frontend developer ';

However, there is a problem with such a copy. That is, if the attribute of the parent object is equal to an array or another object, in fact, the sub-object only obtains a memory address rather than a real copy, so there is a possibility that the parent object will be tampered. See, now add a "skill" attribute to med. Its value is an array.

 
Med. Skills = [''html '', 'css ', 'javascript'];

Through the lightcopy () function, WD inherits the Med.

 
VaR WD = lightcopy (MED );

Then, we add an attribute for the "skill" of WD:

 
WD. Skills. Push ('teamwork ');

What happened? Med's "skills" have also been tampered!

 
Console. log (WD. skills); // 'html ', 'javascript', 'css ', and 'teamwork' console. log (Med. skills); // 'html ', 'javascript', 'css ', 'teamwork'

Therefore, lightcopy () is just a copy of the basic data type. We call this copy a "shortest copy ". This is an early Method for jquery to implement inheritance.

3. Deep copy

The so-called "Deep copy" means to copy arrays and objects in the true sense. Its implementation is not difficult, as long as it recursively calls the "Shallow copy.

 
Function deepcopy (p, c) {var C = C | |{}; for (var I in P) {If (typeof P [I] === 'object ') {c [I] = (P [I]. constructor === array )? []: {}; Deepcopy (P [I], C [I]);} else {C [I] = P [I] ;}} return C ;}

Write as follows:

 
VaR WD = deepcopy (MED );

Now, add an attribute to the parent object and the value is an array. Then, modify this attribute on the sub-object:

Med. Skills = ['html '', 'css ', 'javascript']; WD. Skills. Push ('teamwork ');

In this case, the parent object will not be affected.

 
Console. log (WD. skills); // 'html', 'css ', 'javascript', and 'teamwork' console. log (Med. skills); // 'html', 'css ', 'javascript'

Currently, the jquery library uses this inheritance method.

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.