Inheritance is important in most languages. JavaScript is a prototype-based language, this means that the object can inherit directly from other objects. Here are some common js inheritance.
- Prototype inheritance chain
function Father(){ this.status = true; } Father.prototype.getSuper = function(){ return this.status; }; function Son(){ this.substatus = false; } //继承了 SuperType Son.prototype = new Father(); Son.prototype.getSub = function (){ return this.substatus; }; var instance = new Son(); alert(instance.getSuper()); //true
- Borrowing constructor inheritance
function Father(){ this.colors = [1,2,3]; } function Son(){ //继承了 Father Father.call(this); } var instance1 = new Son(); instance1.colors.push(4); alert(instance1.colors); //"1,2,3,4" var instance2 = new Son(); alert(instance2.colors); //"1,2,3"
- A combination of inheritance
function Father (name) { the this .name = name; } Father.prototype.sayName = function () { Alert ( the this .name); }; function Son (name, Age) { // inherited properties SuperType.call ( the this , name); the this .age = Age; } Son.prototype = new new father (); // prototype parent class subclasses directed Son.prototype.constructor = son; // to point to themselves subclass constructor Son.prototype. sayAge = function () { Alert ( the this.age); }; var instance = new Son("lh", 19); instance1.sayName(); //"lh"; instance1.sayAge(); //19
- Prototypal inheritance
function object(o){ function F(){} F.prototype = o; return new F(); } var person = { name: "lh", loves: ["a", "b", "c"] }; var anotherPerson = object(person); anotherPerson.name = "Greg"; anotherPerson.friends.push("d"); alert(person.loves); //"a,b,c,d"
Object and method herein the Object.create () method analogous.
- Parasitic inheritance
function Object (O) { function F. () {} F.prototype = O; return new new F. (); } function createAnother (obj) { var clone = Object (obj); // Create a new object by calling the function clone. = say function () { // for the method of adding the object Alert ( "Hi" ); }; return clone; // return the object } var Person = { name: "LH" , Loves: [ "A", "B "," C " ] }; var anotherPerson = createAnother(person); anotherPerson.say(); //"hi"
- Combined parasitic inheritance
function inheritPrototype(son, father){ var prototype = Object.create(father.prototype); son.prototype = prototype;
prototype.constructor = son; } function Father(name){ this.name = name; } Father.prototype.sayName = function(){ alert(this.name); }; function Son(name, age){ Father.call(this, name); this.age = age; } inheritPrototype(Son, Father); - Use es6 achieve
class Father{ constructor(x, y) { this.x = x; this.y = y; } } class son extends Father{ constructor(x, y, age) { super(x, y); // 调用父类的constructor(x, y) this.age= age; } toString() { return this.color + ' ' + super.toString(); // 调用父类的toString() } }
Subclass inherits the parent class constructor must first call the super () method to access this, otherwise it will error.