Let's first look at the inheritance of JS classes
<!DOCTYPE html><html><head> <meta charset="UTF-8"> <title>Inheritance of JS class</title></head><body> /* -- Classical inheritance- */ <script type="text/javascript"> //Declare a superclass var Animal = function(name) { this.name = name; } //Add the method Animal.prototype.Eat = function() { console.log(this.name + "Eat"); }; //Instance this supervar a = new Animal("Animal"); //Create the constructor object class var Cat = function(name, sex) { //This class should call the constructor of the superclass Animal and pass the parameter name to it Animal.call(this, name); this.sex = sex; } //The prototype object of this subclass is equal to the instance of the superclass Cat.prototype = new Animal(); //Because the prototype object of the subclass is equal to the instance of the superclass, the method prototype.constructor is also equal to the superclass constructor console.log(Cat.prototype.constructor); //This is a reference to the Animal superclass, so you must reassign it to yourself Cat.prototype.constructor = Cat; console.log(Cat.prototype.constructor); //The subclass itself adds the getSex method Cat.prototype.getSex = function() { return this.sex; } //Instanced this subclass var _m = new Cat('cat', 'male'); //Own method console.log(_m.getSex()); //male //Inherit the superclass method console.log(_m.Eat()); //cat </script></body></html>Let's look at JS prototype inheritance
<!DOCTYPE html><html><head> <meta charset="UTF-8"> <title>JS prototype inheritance</title></head><body> <!--Prototype inheritance--> <script type="text/javascript"> //clone() function is used to create a new class Person object var clone = function(obj) { var _f = function() {}; //This sentence is the core of prototype inheritance. The prototype object of the function is the object literal_f.prototype = obj; return new _f; } //Declare an object literal first var Animal = { somthing: 'apple', eat: function() { console.log("eat " + this.somthing); } } //No need to define a subclass of Person, just perform a cloning var Cat = clone(Animal); //You can directly obtain the default value provided by Person, or you can add or modify attributes and methods console.log(Cat.eat()); Cat.somthing = 'orange'; console.log(Cat.eat()); //Declare the subclass and perform a cloning var Someone = clone(Cat); </script></body></html>We can experiment. The inheritance of JS class children.constructor==father returns true, while the inheritance of prototype children.constructor==father returns false;
The above brief analysis of JS prototype inheritance and class inheritance is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.