How JavaScript implements Inheritance

Source: Internet
Author: User
Tags mathematical constants

To implement inheritance in JavaScript is to implement three layers of meaning:
1. Instances of subclasses can share methods of parent class;
2, subclasses can override the parent class method or extend the new method;
3, subclasses, and parent classes are "types" of child class instances.

In JavaScript, inheritance is not supported directly from the syntax, but it is possible to implement inheritance through a simulated approach, following a summary of several ways to implement inheritance:
1. Structural Inheritance Law
2. Prototype Inheritance Law
3. Example Inheritance Law
4. Copy Inheritance Law

1, the construction of inheritance law:
Executes the constructor of the parent class in the subclass.

1<script language= "JavaScript" >
2 <!--
3 function Dwn (s)
4 {
5 document.write (s+ ' <br/> ');
6}
7
8//Define a collection type
9 function Collection (size)
10 {
One this.size = function () {return size}; Public methods, which can be inherited
12}
13
14//define a _collection type
function _collection (_size)
16 {
This._size = function () {return _size}; Public methods, which can be inherited
18}
19
Collection.prototype.isEmpty = function ()//static method, cannot be inherited
21 {
return this.size () = = 0;
23}
24
25//Define a ArrayList type, which "inherits" the Colleciton type
function ArrayList ()
27 {
m_elements var = []; Private member, cannot be inherited
m_elements = array.apply (m_elements,arguments);
30
//arraylist Type Inheritance Colleciton
This.base = Collection;
This.base.call (this,m_elements.length);
34
This.base = _collection; Multiple-State inheritance can be implemented
This.base.call (this,m_elements.length);
37
This.add = function ()
39 {
M_elements.push.apply return (m_elements,arguments);
41}
42
This.toarray = function ()
44 {
M_elements return;
46}
47}
48
ArrayList.prototype.toString = function ()
50 {
Wuyi return This.toarray (). toString ();
52}
53
54//Define a SortedList type, which inherits the ArrayList type
function SortedList ()
56 {
//sortedlist Type Inheritance ArrayList
This.base = ArrayList;
This.base.apply (this,arguments);
60
This.sort = function ()
62 {
The var arr = This.toarray ();
Arr.sort.apply (arr,arguments);
65}
66}
67
68//Construct a ArrayList
var a = new ArrayList (n/a);
Dwn (a); The
Dwn (A.size ()); 3 A inherits the size () method from collection
Dwn (A.isempty); Undefined but a does not inherit to the IsEmpty () method
73
Dwn (A._size ()); 3 multiple-State inheritance can be implemented
75
76//Construct a SortedList
$ var b = new SortedList (3,1,2);
Dwn (B.toarray ());
B.add (4,0); b inherits the Add () method from ArrayList
Dwn (B.toarray ()); b inherited the ToArray () method from ArrayList
Bayi B.sort (); b Implement the sort () method yourself
Dwn (B.toarray ());
Dwn (b);
Dwn (B.size ()); b inherits the size () method from collection
//-->
</SCRIPT>

2, the prototype inheritance law:
JavaScript is a prototype-based language.
To understand what "prototype inheritance" is, let's look at the features of prototype: The biggest feature of prototype is the ability to have object instances share the properties of a prototype object, so if a pair
Like a prototype of a type, we say that all instances of this type are prototypes of this object. At this point, the type of the object can actually be used as the type of an instance that is a prototype of this object.
If: The object of the point class is a prototype of the POINT2D type (Point2d.prototype = new
Point (2)), then all instances of POINT2D are prototyped with the object of the class. In this case, the point class is actually a class that can act as an object of type point2d
Type, which is equivalent to the "inherited" point type of point2d.
See Example:

1 <script language= "JavaScript" >
2 <!--
3 function Dwn (s)
4 {
5 document.write (s+ "<br/>");
6}
7
8 function point (Dimension)//define a point class
9 {
Ten this.dimension = dimension;
11}
12
Point.prototype.distance = function ()//static method, can be inherited
14 {
return this.dimension*2;
16}
17
function point2d (x, y)//define a POINT2D class
19 {
this.x = x;
This.y = y;
22}
23
Point2d.prototype = new Point (2); Run the prototype inheritance method to enable point2d to inherit the point
25
function Point3D (x, y, z)//define Point3D class
27 {
this.x = x;
This.y = y;
This.z = Z;
31}
32
Point3d.prototype = new Point (3); Point3D inheriting the Point class
34
var p2 = new Point2d; Constructs a Point2d object
36
PNS var p3 = new Point3D (n/a); Constructs a Point3D object
38
Dwn (p2.dimension); 2
Dwn (p3.dimension); 3
Dwn (P2.distance ()); 4 can inherit static methods
Dwn (P3.distance ()); 6 can inherit static methods
43
Dwn (P2 instanceof point2d); P2 is the Point2d object
Dwn (P2 instanceof point); POINT2D inherited Point,p2 is a point object
46
Dwn (P3 instanceof Point3D); P3 is the Point3D object
Dwn (P3 instanceof point); Point3D inherited Point,p3 is a point object
49
//-->
Wuyi </SCRIPT>

3. Example Inheritance Law
There are various shortcomings in the method of structural inheritance and prototype inheritance, such as:
There is no way to inherit a static method of a type, so it does not inherit the core object of JavaScript well.
Although the prototype inheritance method can inherit static methods, it is still not good to inherit the non-enumerable methods in the core object.
Among them, JavaScript core objects include:
Array to represent the arrays.
Boolean to express the bool value.
Date expression dates.
function specifies a string of JavaScript code that can be compiled into a function.
Math provides basic mathematical constants and functions, as its PI attribute contains the value of π.
Number to represent a real value.
object contains the basic functionality shared by all JavaScript objects.
RegExp describes a regular expression and includes a shared static property of all regular expression objects.
String describes a JavaScript string.
(1) Limitations of the construction of inheritance law:

1 <script language= "JavaScript" >
2 <!--
3 function MyDate ()
4 {
5 this.base = Date;
6 this.base.apply (this,arguments);
7}
8
9 var date = new MyDate ();
Ten alert (date.togmtsring ()); Object does not support this method or property
Some methods of the 11//Core object (Date) cannot be constructed because the core object is not assigned or initialized in the constructor like our custom generic object.
//-->

(2) Limitations of prototype inheritance

1 <script language= "JavaScript" >
2 <!--
3 function MyDate ()
4 {
5
6}
7 Mydate.prototype = new Date ();
8 var date = new MyDate ();
9 Alert (date.togmtsring ()); ' [Object] is not a Date object '
Ten//-->
</SCRIPT>

The above illustrates the limitations of "structural inheritance" and "Prototype Inheritance" (one of the limitations: not very good for inheriting core objects), and the following describes how to inherit core objects using instance inheritance.

Before the introduction, first understand the following about constructors:
Constructors typically do not return a value, they simply initialize the object passed in by the this value, and nothing is returned. If the function has a return value, the returned object becomes the value of the new expression.

1 <script language= "JavaScript" >
2 <!--
3 function Dwn (s)
4 {
5 document.write (s+ ' <br/> ');
6}
7 function MyDate ()
8 {
9 var instance = new Date (); Instance is a newly created Date object
Instance.printdate = function ()//instance Extended PrintDate () method on Date Object
11 {
Dwn (Instance.tolocalestring ());
13}
instance return; Returns the instance as the return value of the constructor
15}
16
* var date = new MyDate ();
Dwn (Date.togmtstring ());
Date.printdate ();
Dwn (date instanceof mydate); False
Dwn (date instanceof date); True
22//The constructor of the object will be the constructor of the actual constructed object (new Date ()), not the constructor of the type itself (New MyDate ())
//-->
</SCRIPT>

4. Copy Inheritance Law

The copy inheritance method implements inheritance through the copying of object properties.

1 <script language= "JavaScript" >
2 function point (Dimension)
3 {
4 this.dimension = dimension;
5}
6
7 var point2d = function (x, y)
8 {
9 this.x = x;
Ten this.y = y;
11}
12
Point2d.extend = function ()
14 {
The var p = new Point (2);
(Var each in P)//The properties of the object are copied one-to-one.
17 {
//this[each] = P[each];
This.prototype[each] = P[each];
20}
21}
Point2d.extend ();
//alert (point2d.dimension);
alert (Point2D.prototype.dimension);
</script>

How JavaScript implements Inheritance

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.