This article analyzes the usage of JS inheritance with examples. Share it with everyone for your reference. The specific analysis is as follows:
Inheritance: Subclasses do not affect the parent class. Subclasses can inherit some functions of the parent class (code reuse)
Inheritance of attributes: call the constructor of the parent class call
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); //如果用Worker.prototype=Person.prototype的话,会造成引用相同的问题 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(); // 这样继承会继承父级的不必要属性 function F(){}; F.prototype = Person.prototype; Worker.prototype = new F(); //通过建立一个临时构造函数来解决 ,也称为代理函数 var coder = new Worker('MAGICFLY','START'); coder.showName();
3. Prototypal inheritance
var a = { name : '小明' }; var b = cloneObj(a); b.name = '小强'; //alert( b.name ); alert( a.name ); function cloneObj(obj){ var F = function(){}; F.prototype = obj; return new F(); }
Applicable conditions
Copy inheritance: Universal type, can be used with or without new
Class inheritance: new constructor
Prototypal inheritance: Object without new
I hope this article will be helpful to everyone’s JavaScript programming design.