Detailed Explanation of Three Inheritance Modes of js

  • 2021-07-13 04:02:43
  • OfStack

1. js prototype (prototype) implements inheritance

The code is as follows


<body> 
<script type="text/javascript"> 
 function Parent(name,age){
   this.name=name;
   this.age=age;
   this.sayHi=function(){
    alert("Hi, my name is "+this.name+", my age is "+this.age);
   }
  }
//Child Inheritance Parent
  function Child(grade){
   this.grade=grade;
   this.sayGrade=function(){
    alert("My grade is "+this.grade);
   }
  }
  Child.prototype=new Parent(" Xiao Ming ","10");/////////// 
  var chi=new Child("5");
  chi.sayHi();
  chi.sayGrade();
</script> 
</body> 

2. Constructor Implementation Inheritance

The code is as follows:


<body> 
<script type="text/javascript"> 
 function Parent(name,age){
   this.name=name;
   this.age=age;
   this.sayHi=function(){
    alert("Hi, my name is "+this.name+", my age is "+this.age);
   }
  }
//Child Inheritance Parent 
  function Child(name,age,grade){
   this.grade=grade;
   this.sayHi=Parent;///////////
   this.sayHi(name,age);
   this.sayGrade=function(){
    alert("My grade is "+this.grade);
   }
  }
  var chi=new Child(" Xiao Ming ","10","5");
  chi.sayHi();
  chi.sayGrade();
</script> 
</body> 

3. call, apply implement inheritance----very convenient!

The code is as follows:


<body> 
<script type="text/javascript"> 
 function Parent(name,age){
   this.name=name;
   this.age=age;
   this.sayHi=function(){
    alert("Hi, my name is "+this.name+", my age is "+this.age);
   }
  }
  function Child(name,age,grade){
   this.grade=grade;
   // Parent.call(this,name,age);/////////// 
   // Parent.apply(this,[name,age]);///////////  Can be 
   Parent.apply(this,arguments);/////////// 
   this.sayGrade=function(){
    alert("My grade is "+this.grade);
   }
  // this.sayHi=function(){
   //  alert("Hi, my name is "+this.name+", my age is "+this.age+",My grade is "+this.grade);
   // }
  }
  var chi=new Child(" Xiao Ming ","10","5");
  chi.sayHi();
  chi.sayGrade();
</script> 
</body> 

Related articles: