JavaScript Object-Oriented Programming Basics: Inheriting _js object-oriented

Source: Internet
Author: User
We see how straightforward the concept of inheritance here is, "copy the prototype of a class to another class", OK, code is cheap, look at the codes:

function Class1 () {}
function Class2 () {}
Class2.prototype = Class1.prototype;
Class2.moreproperty1 = "Class 2 additional string";
Class2.moremethod1 = function () {alert (' Class 2 additional method ');}
/*
So, first of all, the CLASS2 has the same prototype as Class1, regardless of the constructor, two classes are equivalent.
Subsequently, the Class2 was given two additional methods through prototype. So Class2 is based on Class1.
Attributes and methods are added, which implements the inheritance of the class.
*/

function Test () {
var obj = new Class2 ();
JavaScript provides the instanceof operator to determine whether an object is an instance of a class
Alert (obj instanceof Class2); True
Alert (obj instanceof Class1); // ?
}

Run code, the result is not in our expected? On the surface, the above implementation is completely feasible, JS can also correctly understand and realize this inheritance relationship, obj is also Class1 and class2 examples, but in essence otherwise (our study is to know the purpose is to know the reason why). JS This understanding is actually based on a very simple strategy, look at the following code, first use prototype let Class2 inherited from Class1, and then in Class2 repeatedly define method methods:

Define Class1
function Class1 () {
Constructors
}
Define the members of the Class1
Class1.prototype = {
M1:function () {//Method 1
Alert ("Class1 method1");
}
}
Define Class2
function Class2 () {
Constructors
}
Let Class2 inherit from Class1
Class2.prototype = Class1.prototype;

Repeat definition method for Class2
Class2.prototype.method = function () {
Alert ("Whose Method2?") Class1 or Class2 ");
}
Create an instance of two classes
var obj1 = new Class1 ();
var obj2 = new Class2 ();

function Test () {
Method methods that call two objects individually
Obj1.method ();
Obj2.method ();
}

From the execution of the Code, the results of the method methods running in class1,2 are the same.

Thus, when the prototype changes to Class2, Class1 prototype also changed, even if the class2 of prototype increase or decrease some members, Class1 members also changed. So Class1 and Class2 are just two different classes of constructors, and they keep the same member definitions. Here, believe that the reader has found the secret: Class1 and Class2 prototype is exactly the same, is a reference to the same object. In fact, from this assignment statement can be seen:
Let Class2 inherit from Class1
Class2.prototype=class1.prototype;
In JS, except for the basic data types (numbers, strings, Boolean types, etc.), all assignments and function parameters are reference passes, not value passes. So the above statement simply lets the Class2 prototype object refer to the Class1 prototype, resulting in a consistent effect of the class member definition. We also see the execution mechanism of the instanceof operator, which is to judge whether an object is an prototype instance, because the obj1 and obj2 are all corresponding to the same prototype, so they instanceof the same result. Thus, using prototype reference copy to implement inheritance is not the right approach. But in the case of not strict requirements, but also a reasonable way, the only constraint is not allowed to class members of the coverage definition (here is actually JS flexibility embodiment). In fact, we can fully use the reflection mechanism and prototype to implement JS correct class inheritance:

function Class1 () {
Constructors
}
Class1.prototype = {
Method:function () {
Alert ("Method1");
},
Method2:function () {
Alert ("Method2");
}
}
function Class2 () {
Constructors
}

Let Class2 inherit from Class1
For (var p in Class1.prototype) {
CLASS2.PROTOTYPE[P] = class1.prototype[p]; Using reflection mechanism and prototype to realize inheritance
}

Method of overriding definition Class1
Class2.prototype.method = function () {
Alert ("Class2 new Method1");
}


Create an instance of two classes
var obj1 = new Class1 ();
var obj2 = new Class2 ();

function Test () {
Method methods that call two objects individually
Obj1.method ();
Obj2.method ();
Method2 method that calls two objects individually
OBJ1.METHOD2 ();
OBJ2.METHOD2 ();
}

As seen from the run result, the repeatedly defined method in Obj2 has overridden the inherited method methods, while the METHOD2 methods are not affected. And the method in Obj1 still retains its original definition. In this way, the inheritance of the class with the correct meaning is achieved. For easy development, you can add a common method for each class to implement the inheritance of the class:

To add a static method to a class inherit represents inheriting from a class
Function.prototype.inherit = function (BaseClass) {
For (var p in Baseclass.prototype) {
this. Prototype[p] = baseclass.prototype[p];
}
}

function Class1 () {
Constructors
}
Class1.prototype = {
Method:function () {
Alert ("Method1");
},
Method2:function () {
Alert ("Method2");
}
}
function Class2 () {
Constructors
}

Let Class2 inherit from Class1
For (var p in Class1.prototype) {
CLASS2.PROTOTYPE[P] = class1.prototype[p]; Using reflection mechanism and prototype to realize inheritance
// }

Class2.inherit (Class1); Equivalent to the one for loop that is commented out above

Method of overriding definition Class1
Class2.prototype.method = function () {
Alert ("Class2 new Method1");
}


Create an instance of two classes
var obj1 = new Class1 ();
var obj2 = new Class2 ();

function Test () {
Method methods that call two objects individually
Obj1.method ();
Obj2.method ();
Method2 method that calls two objects individually
OBJ1.METHOD2 ();
OBJ2.METHOD2 ();
}

The above code makes logic clearer and easier to understand. The disadvantage of inheriting in this way is that when you add a class member definition to a class2, you cannot assign a value directly to prototype, and you can only assign a property to it, for example, you cannot:
class2.prototype={
Member definition
}
and only for:
Class2.prototype.propertyname=somevalue;
Class2.prototype.methodname=function () {
Statement
}

Thus, the implementation of inheritance is still at the expense of certain code readability. Is there "not only the base class can be directly assigned to the property with the object, and in the derived class can also be implemented, so that the logic of the code clearer, but also more reflect the object-oriented language features" JS inheritance mode? How tempting the quotes are, keep on learning.

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.