Forget version -ES3, ES5 implementation inheritance way
Parasitic combinatorial inheritance
Constructor inheritance: in the subclass constructor to call the implementation of the parent class constructor to achieve all attribute method exclusive, but can not achieve attribute, method sharing; Prototype chain inheritance: the prototype of the subclass points to the instance of the parent class to achieve prototype sharing; Parasitic inheritance: Because combinatorial inheritance calls the parent class twice (constructor inheritance and prototype chain inheritance combination), the implementation of parasitic inheritance is similar to factory mode, which calls a function that only encapsulates the inheritance process, namely object.create below
JS code
/ / parent
function Person(name) {
this.name = name;
}
Person.prototype.sayName = function() {
console.log('person name:'.this.name);
}
/ / the child
function Student(name, personName) {
Person.call(this, personName);
this.name = name;
}
Object. Create is not supported until after ES5, so in ES3 you can write your own mock method
if(!Object.create){
Object.create = function(proto){
function F(){}
F.prototype = proto;
return newF(); }}// Error
// 1. The Student attribute will also exist in Person
// Student.prototype = Person.prototype;
// 2. New Person() gets an instance of Person, which points to Person.prototype and calls the constructor. For example, what's the name of new Person()? Student is just a class that hasn't been instantiated yet. Isn't it weird to call the constructor and create the instance just for inheritance
// Student.prototype = new Person();
// A relatively ideal way to write
// Object.create creates an empty Object and the Object prototype points to Person.prototype. This ensures that the methods on Person.prototype are inherited, and that Student. Prototype has its own empty Object and its modifications will not affect the properties on the prototype chain
Student.prototype = Object.create(Person.prototype);
Student.prototype.sayName = function() {
console.log('student name:'.this.name);
}
Student.prototype.constructor = Person;
var person = new Person('person');
person.sayName(); // person name: person
var student = new Student('student'.'person');
student.sayName(); // student name: student
Copy the code
OK, that completes a bit of classic inheritance theory code.