This article analyzes the usage of JS inheritance. Share to everyone for your reference. The specific analysis is as follows:
Inheritance: Subclasses do not affect the parent class, and subclasses can inherit some of the functions of the parent class (code reuse)
Inheritance of a property: Calling the constructor of the parent class call
Method inheritance: For in: Copy Inheritance (jquery is also a copy-inherited 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 you use Worker.prototype=person.prototype, it will cause references to 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 inherits the unnecessary property
function F () {} of the parent;
F.prototype = Person.prototype;
Worker.prototype = new F ();
Solved 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: ' Xiaoming '
};
var B = Cloneobj (a);
B.name = ' Xiao Qiang ';
alert (b.name);
alert (a.name);
function Cloneobj (obj) {
var F = function () {};
F.prototype = obj;
return new F ();
}
Applicable situation
Copy inheritance: A generic type that has new or no new is available
Class Inheritance: New constructor
Prototype inheritance: An object without new
I hope this article will help you with your JavaScript programming.