当前位置: 移动技术网 > IT编程>开发语言>JavaScript > js的三种继承方式详解

js的三种继承方式详解

2019年03月29日  | 移动技术网IT编程  | 我要评论

1.js原型(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> 

2.构造函数实现继承 

代码如下:

<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> 

3.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> 

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持移动技术网!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网