This article analyzes the usage of JS inheritance. Share it for your reference. The specific analysis is as follows:
Inheritance: The subclass does not affect the parent class. The subclass can inherit some functions of the parent class (code reuse)
Inheritance of properties: Call the constructor of the parent class
Method inheritance: for in: copy inheritance (jquery also uses copy inheritance extend)
1. Copy Inheritance
function Person (name){ this.name = name;}Person.prototype.showName =function (){ alert(this.name);}function Worker(name,job){ Person.call(this,name); this.job = job;}extend(Worker.prototype, Person.prototype);//If Worker.prototype=Person.prototype, it will cause the same reference function extend(obj1,obj2){ for(var i in obj2){ obj1[i] = obj2[i] }}var coder = new Worker('magicfly','frontEnd');coder.showName();2. Class inheritance
function Person (name){ this.name = name;}Person.prototype.showName =function (){ alert(this.name);}function Worker(name,job){ Person.call(this,name); this.job = job;}//Worker.prototype = new Person();//Inheritance will inherit the unnecessary attributes of the parent function F(){};F.prototype = Person.prototype;Worker.prototype = new F();//Solve by establishing a temporary constructor, also known as the proxy function var coder = new Worker('MAGICFLY','START');coder.showName();3. Prototype inheritance
var a = { name : 'Xiao Ming'};var b = cloneObj(a);b.name = 'Xiaoqiang';//alert( b.name );alert( a.name );function cloneObj(obj){ var F = function(){}; F.prototype = obj; return new F();}Applicable
Copy inheritance: General-purpose type can be used when new or no new
Classification inheritance: new constructor
Prototype inheritance: Object without new
I hope this article will be helpful to everyone's JavaScript programming.