JavaScript inheritance mechanism example detailed _javascript skill

Source: Internet
Author: User

This example describes the JavaScript inheritance mechanism. Share to everyone for your reference. The specific analysis is as follows:

Beginner JavaScript is generally difficult to understand the inheritance mechanism of JavaScript language it does not have the concept of "subclass" and "parent class", nor is there a distinction between "class" and "instance" (instance), relying on a peculiar "prototype chain" (prototype Chain) mode, to implement inheritance.

I spent a lot of time studying this part and taking a lot of notes. But all belong to the forced memory, can not fundamentally understand.

One, how to create a class

Suppose there is a class named person as follows:

Copy Code code as follows:
var person = function (name, age) {
THIS.name = name;
This.age = age;
}
Person.prototype.getName = function () {
return this.name;
}

As above: person on behalf of all the people on Earth, everyone has these two basic attributes: Name and age; now we're going to implement a student class, and then we know that the student is also a person, and the student also has attributes such as name and time; Now the question is how can we put this relationship together?
Let's take a look at how the pure object-oriented language is done (e.g., ACTIONSCRPT3)
Copy Code code as follows:
Class Students extend person {}; Quite simply, a line of code; more precisely a word--extend

How can I change to JS?

In the interpretation of the inheritance mechanism JS before the implementation of the first understanding of JS prototype chain:

Copy Code code as follows:
var person = new Person (' POISED-FLW ', 21);
Person.getname (); "POISED-FLW"

How is the GetName () method performed on the above? First in the person this function to find out whether there is getname () This method, found no, and then go to Person.prototype search, found that there! And then call, if not? Continue to follow the same approach along the prototype until you find a way or reach the top of the prototype chain!

For example, there is now a constructor called Dog that represents the prototype of a dog object.

Copy Code code as follows:
function DOG (name) {
THIS.name = name;
}

When you use new for this constructor, an instance of a dog object is generated.
Copy Code code as follows:
var Doga = new DOG (' hairy ');
alert (doga.name); Nagymaros

Note the This keyword in the constructor, which represents the newly created instance object.

Disadvantages of the new operator

The disadvantage of generating instance objects with constructors is that you cannot share properties and methods.
For example, in the constructor of a dog object, set the common property species of an instance object.

Copy Code code as follows:
function DOG (name) {
THIS.name = name;
this.species = ' canine Division ';
}

Then, two instance objects are generated:
Copy Code code as follows:
var Doga = new DOG (' hairy ');
var dogb = new DOG (' Er Mao ');

The species property of the two objects is independent, and modifying one does not affect the other.
Copy Code code as follows:
doga.species = ' cat family ';
alert (dogb.species); Show "canine", not affected by Doga

Each instance object has its own copy of the properties and methods. This not only can not do data sharing, but also a huge waste of resources.

So: The inheritance of the idea: through JS-specific prototype chain to implement the inheritance mechanism!

Iv. inheritance based on prototype chain

1. Direct Inheritance Implementation

Copy Code code as follows:
var Students = function (name, age, SID) {
Person.call (this, name, age);
This.sid = SID;
}
Students.prototype = new Person (); Put the person on the students prototype chain to implement the inheritance mechanism
Students.prototype.constructor = Students;
Students.prototype.getResults = function () {
Get the students ' grades
}

Must not be less Students.prototype.constructor = students this line! , when defining a constructor, its default prototype is an object instance, and the prototype constructor property is automatically set to the function itself!!! If you manually set prototype to another object, the new object naturally does not have the Contructor value of the original object, so you need to reset its constructor property. Such as:
Copy Code code as follows:
var Test = function () {
This.time = "Now";
}
Console.log (Test.prototype); Object {} An empty
Console.log (Test.prototype.constructor); function () {this.time = ' now ';}, and functions themselves
If you change the prototype property of the test manually
Test.prototype = {
Somefunc:function () {
Console.log (' Hello world! ');
}
};
Console.log (Test.prototype.constructor); function Object () {[native code]}
Then you will find that you are completely wrong, so you need to change the prototype property manually when changing its constructor point;

The above test will tell you why you want to modify the constructor value.

2. Encapsulate inherited functions Extend

Copy Code code as follows:
function extend (subclass, superclass) {
var F = function () {};
F.prototype = Superclass.prototype;
Subclass.prototype = new F ();
SubClass.prototype.constructor = subclass;
}

In fact, this function is only a function of the above inheritance process of a package, the difference is:
Inherits only the prototype attribute of the superclass, and does not inherit the property in the superclass constructor;
The advantage of this is that it reduces the cost of going to new constructor!
The problem, of course, is that you can't get subclass to inherit all of superclass's properties without a single function.
Improved:
Copy Code code as follows:
To continue adding one line of code in the students constructor:
Person.call (this, name, age);

V. Summary

The use of JS prototype chain principle, we can easily implement JS inheritance mechanism, although not very strict, but my goal is achieved: Repeat the code as much as possible to appear once!

I hope this article will help you with your JavaScript programming.

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.