This article shares the code related to js type inheritance and prototype inheritance for your reference. The specific content is as follows
1.js class inheritance
/* -- Classical inheritance- */// First declare a superclass function Person(name) {this.name = name;}// Add method to the prototype object of this superclass getName Person.prototype.getName = function() {return this.name;}// Instantize this supervar a = new Person('Darren1')console.log(a.getName());//Darren1// Declare the class function Programmer(name, sex) {// This class should call the constructor of the superclass Person and pass the parameter name to it Person.call(this, name); this.sex = sex;}//The prototype object of this subclass is equal to the instance of the superclass Programmer.prototype = new Person();//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. You can test it yourself. If this step is not available, console.log(Programmer.prototype.constructor is a reference to the Person superclass, so you have to reassign it to your own console.log(Programmer.prototype.constructor);/*function Person(name) {this.name = name;} */Programmer.prototype.constructor = Programmer;console.log(Programmer.prototype.constructor);/*function Programmer(name, sex) {Person.call(this, name); this.sex = sex;} *///The subclass itself adds the getSex method Programmer.prototype.getSex = function() {return this.sex;}//Instanced this subclass var _m = new Programmer('Darren2', 'male');//Own method console.log(_m.getSex());//male//Inherits the superclass method console.log(_m.getName());//Darren22.js prototype inheritance
/* -- Prototype inheritance- *////clone() function is used to create a new class Person object var clone = function(obj) {4var _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 Person = {name: 'Darren',getName: function() {return this.name;}}//No need to define a subclass of Person, just perform a cloning var Programmer = clone(Person);//You can directly obtain the default value provided by Person, or you can add or modify the attributes and methods alert(Programmer.getName())Programmer.name = 'Darren2'alert(Programmer.getName())//Declare the subclass and perform a cloning once var Someone = clone(Programmer);The above is all about this article, I hope it will be helpful for everyone to learn JavaScript programming.