Home > Article > Web Front-end > Detailed explanation of the use of constructor method object impersonation based on JavaScript implementation of inheritance mechanism_Basic knowledge
Ways of inheritance
ECMAScript has more than one way to implement inheritance. This is because the inheritance mechanism in JavaScript is not explicitly specified but implemented through imitation. This means that not all inheritance details are entirely handled by the interpreter. As the developer, you have the right to decide the inheritance method that works best for you. The most primitive inheritance implementation method is object impersonation. This method will be introduced below.
Object impersonation
The core of object impersonation to implement inheritance actually relies on using the this keyword in a function environment. The principle is as follows: the constructor uses the this keyword to assign values to all properties and methods (that is, using the constructor method of class declaration). Because a constructor is just a function, you can make the ClassA constructor a method of ClassB and then call it. ClassB will receive the properties and methods defined in the constructor of ClassA. For example, define ClassA and ClassB in the following way:
function ClassB(sColor) {
}
All new properties and new methods must be defined after removing the line of code for the new method. Otherwise, the relevant properties and methods of the super class may be overridden:
this.name = sName;
this.sayName = function () {
alert(this.name);
};
}
this.newMethod = ClassY;
this.newMethod();
delete this.newMethod;
}
Due to the popularity of this inheritance method, the third version of ECMAScript added two methods to the Function object, namely call() and apply(). Later, many derived methods for implementing inheritance were actually implemented based on call() and apply().