Home  >  Article  >  Web Front-end  >  How to use JS inheritance and multiple inheritance

How to use JS inheritance and multiple inheritance

php中世界最好的语言
php中世界最好的语言Original
2018-05-28 09:46:381925browse

This time I will show you how to use JSInheritance and multiple inheritance, what are the precautions when using JS inheritance and multiple inheritance, the following is a practical case, let’s take a look .

Although the latest EC6 already has class-related functions, from the perspective of popularity and the need to read old code, this knowledge must be understood.

The structure of this article:

① Principle and analysis

② Application after simple encapsulation

1. Inheritance

##① Principle and analysis

First picture:

Use the idea of ​​​​this code to realize inheritance, that is:

var inherit=function(objBase){
    var F=function(){}; //第一步:定义一个函数F
    F.prototype=objBase; //第二步:将传进来的基类对象(objBase)赋给函数F的原型(F.prototype)
    return new F(); //第三步:返回一个F对象(已经具备了objBase特征)
}

② Application after simple encapsulation

Function.prototype.inherit=function(objBase){
    this.prototype=new objBase();
}
var Person=function(){
    this.name="倩倩";
    this.sex="女";
}
var Student=function(){
    this.id="0712";
}
Student.inherit(Person);
var student=new Student();
alert(student.name +","+ student.sex +","+ student.id);

2. Multiple inheritance

① Principle and analysis

Multiple inheritance is to transfer members of multiple objects to the current object

var o1={name:"倩倩"} //对象的字面值
var o2={sex:"女"}
var She=function(){}
She.prototype={};  //先声明
for(var k in o1){
    She.prototype[k]=o1[k];
}
for(var k in o2){
    She.prototype[k]=o2[k];
}
var she=new She();
alert(she.name + "," + she.sex);

② Application after simple encapsulation

Function.prototype.inherits=function(){
    var arr=arguments; //将接收到的arguments对象传给数组arr
    this.prototype={};
    for(var i=0;i<arr.length;i++){
      for(var k in arr[i]){
        var obj=arr[i];
        this.prototype[k]=obj[k];
      }
    }
}
var o1={name:"倩倩"} //对象的字面值
var o2={sex:"女"}
var She=function(){}
She.inherits(o1,o2);
var she=new She();
alert(she.name + "," + she.sex);
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Recommended reading:

How to operate express's default log component morgan

What code specifications for JS have been released by Google

The above is the detailed content of How to use JS inheritance and multiple inheritance. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn