JS inheritance usage instance analysis and js inheritance instance analysis
This article analyzes the usage of JS inheritance. Share it with you for your reference. The specific analysis is as follows:
Inheritance: Child classes do not affect the parent class. Child classes can inherit some features of the parent class (code reuse)
Property inheritance: call the constructor call 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 is used. prototype = Person. prototype causes reference of the same problem 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 (); // This inheritance will inherit the unnecessary attribute function F () {}; F. prototype = Person. prototype; Worker. prototype = new F (); // It is solved by creating a temporary constructor, also known as the proxy function var coder = new Worker ('magicfly ', 'start'); coder. showName ();
3. Prototype inheritance
Var a = {name: 'xiaoming '}; var B = cloneObj (a); B. name = 'xiaoqiang'; // alert (B. name); alert (. name); function cloneObj (obj) {var F = function () {}; F. prototype = obj; return new F ();}
Applicability
Copy inheritance
Class inheritance: new Constructor
Prototype inheritance: objects without new
I hope this article will help you design javascript programs.