JavaScript 实现继承的三种核心方式解析

作者:代码拾荒时间:2026-10-21 20:48:52浏览:447

本文详细解析JavaScript中实现对象继承的三种主要方式:原型链继承、构造函数继承以及利用call和apply方法的继承。通过具体代码示例,对比分析了各方法的实现原理、优缺点及适用场景,帮助开发者根据实际需求选择最合适的继承策略。

原型链继承方式

第一种继承方式是利用JavaScript的原型(prototype)机制来实现。

具体的代码实现如下所示:


<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继承Parent
  function Child(grade){
   this.grade=grade;
   this.sayGrade=function(){
    alert("My grade is "+this.grade);
   }
  }
  Child.prototype=new Parent("小明","10");/////////// 
  var chi=new Child("5");
  chi.sayHi();
  chi.sayGrade();
</script> 
</body> 

构造函数继承方式

第二种方式是通过构造函数来实现继承。

相关的代码示例如下:


<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继承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("小明","10","5");
  chi.sayHi();
  chi.sayGrade();
</script> 
</body> 

利用call和apply实现继承

第三种方式是利用call和apply方法来实现继承,这种方式操作起来非常便捷。

对应的代码实现如下:


<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]);/////////// 都可
   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("小明","10","5");
  chi.sayHi();
  chi.sayGrade();
</script> 
</body> 

以上内容涵盖了JavaScript中主要的三种继承实现方式,希望这些内容能对读者的学习或工作有所帮助,同时也感谢大家的支持。

作者最新文章