Class Inheritance:
A "class" Student was created with the function constructor, and a method SayHello was defined on the Student prototype, then a "class" Primarystudent was created, and the primarystudent was initialized with apply ().
Then let the prototype of primarystudent equal to the object created by student, and point the constructor on the Primarystudent prototype to the current "class", i.e. Primarystudent, and note the red bold part.
1 functionStudent (name) {2 This. Name =name;3 }4Student.prototype.sayHello =function(){5Console.log ( This. Name);6 }7 functionprimarystudent (name) {8Student.apply ( This, arguments);9 }Ten primarystudent.prototype = new Student (); OnePrimaryStudent.prototype.constructor =primarystudent; A varStu =NewPrimarystudent ("Yxz"); -Stu.sayhello ();//Output YXZ
Prototype Inheritance:
The key difference between prototype inheritance and "Class" Inheritance lies in the red bold part below, where an empty function f is defined, then the prototype prototype of student is assigned to the prototype prototype of F, and then
Execute Primarystudent.prototype = new F ().
1 functionStudent (name) {2 This. Name =name;3 }4Student.prototype.sayHello =function(){5Console.log ( This. Name);6 }7 varF =function(){8 9 }Ten functionprimarystudent (name) { OneStudent.apply ( This, arguments); A } - F.prototype = student.prototype;14 Primarystudent.prototype = new F (); thePrimaryStudent.prototype.constructor =primarystudent; - varStu =NewPrimarystudent ("Yxz"); -Stu.sayhello ();
"Class" Inheritance and prototype inheritance in JS