Home > Web Front-end > JS Tutorial > body text

A brief discussion on the implementation of JavaScript inheritance mechanism

高洛峰
Release: 2016-11-25 15:34:54
Original
839 people have browsed it

Object impersonation method implementation:

[javascript]
function Human() { //Define the Human class
this.species = "Human" ;
}
function Sex(sex) { //Define Sex class
this.sex = sex;
}
function Chinese(name,sex ) {
this.name = name;
this.newMethod1 = Human; //Object impersonation, pointing to the Human object
this.newMethod1(); //Call the method to achieve inheritance
delete this.newMethod1; //Delete the object Reference to avoid incorrect calls

this.newMethod2 = Sex; //Object impersonation, pointing to the Sex object
this.newMethod2(sex); //Call the method to achieve inheritance
delete this.newMethod2; //Delete the reference to the object, Avoid incorrect calls
}
var chin1 = new Chinese("Xiao Ming", "Male");
function Human() { //Define Human Class
this.species = "Human";
}
function Sex(sex) { //Define Sex class
this.sex = sex;
}
function Chinese(name,sex) {
this.name = name;
this.newMethod1 = Human; //Object impersonation, pointing to the Human object
this.newMethod1(); //Call the method to achieve inheritance
delete this .newMethod1; //Delete the reference to the object to avoid incorrect calls

this.newMethod2 = Sex; //Object impersonation, pointing to the Sex object
this.newMethod2(sex); //Call the method to achieve inheritance
delete this.newMethod2 ; //Delete the reference to the object to avoid incorrect calls
}
var chin1 = new Chinese("Xiao Ming", "Male");

The method of object impersonation is very simple and easy to understand. The principle is to use method calls. Implement the definition of attributes within the function.

Moreover, object impersonation can also achieve multiple inheritance. But there are also disadvantages.

As follows:


[javascript]

Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template