扣丁学堂JavaScript实现面向对象继承五种方式小详解

2018-07-23 14:30:33 403浏览

今天扣丁学堂小编给大家整理了一篇关于Java培训之JS实现面向对象继承方式的详解,首先js是门灵活的语言,实现一种功能往往有多种做法,ECMAScript没有明确的继承机制,而是通过模仿实现的,根据js语言的本身的特性,js实现继承有以下通用的几种方式:



1.使用对象冒充实现继承(该种实现方式可以实现多继承)

实现原理:让父类的构造函数成为子类的方法,然后调用该子类的方法,通过this关键字给所有的属性和方法赋值

  functionParent(firstname)
  {
  this.fname=firstname;
  this.age=40;
  this.sayAge=function()
  {
  console.log(this.age);
  }
  }
  functionChild(firstname)
  {
  this.parent=Parent;
  this.parent(firstname);
  deletethis.parent;
  this.saySomeThing=function()
  {
  console.log(this.fname);
  this.sayAge();
  }
  }
  varmychild=newChild("李");
  mychild.saySomeThing();

2.采用call方法改变函数上下文实现继承(该种方式不能继承原型链,若想继承原型链,则采用5混合模式)

实现原理:改变函数内部的函数上下文this,使它指向传入函数的具体对象

  functionParent(firstname)
  {
  this.fname=firstname;
  this.age=40;
  this.sayAge=function()
  {
  console.log(this.age);
  }
  }
  functionChild(firstname)
  {
  this.saySomeThing=function()
  {
  console.log(this.fname);
  this.sayAge();
  }
  this.getName=function()
  {
  returnfirstname;
  }
  }
  varchild=newChild("张");
  Parent.call(child,child.getName());
  child.saySomeThing();

3.采用Apply方法改变函数上下文实现继承(该种方式不能继承原型链,若想继承原型链,则采用5混合模式)

实现原理:改变函数内部的函数上下文this,使它指向传入函数的具体对象

  functionParent(firstname)
  {
  this.fname=firstname;
  this.age=40;
  this.sayAge=function()
  {
  console.log(this.age);
  }
  }
  functionChild(firstname)
  {
  this.saySomeThing=function()
  {
  console.log(this.fname);
  this.sayAge();
  }
  this.getName=function()
  {
  returnfirstname;
  }
  }
  varchild=newChild("张");
  Parent.apply(child,[child.getName()]);
  child.saySomeThing();

4.采用原型链的方式实现继承

实现原理:使子类原型对象指向父类的实例以实现继承,即重写类的原型,弊端是不能直接实现多继承

  functionParent()
  {
  this.sayAge=function()
  {
  console.log(this.age);
  }
  }
  functionChild(firstname)
  {
  this.fname=firstname;
  this.age=40;
  this.saySomeThing=function()
  {
  console.log(this.fname);
  this.sayAge();
  }
  }
  Child.prototype=newParent();
  varchild=newChild("张");
  child.saySomeThing();

5.采用混合模式实现继承

  functionParent()
  {
  this.sayAge=function()
  {
  console.log(this.age);
  }
  }
  Parent.prototype.sayParent=function()
  {
  alert("thisisparentmethod!!!");
  }
  functionChild(firstname)
  {
  Parent.call(this);
  this.fname=firstname;
  this.age=40;
  this.saySomeThing=function()
  {
  console.log(this.fname);
  this.sayAge();
  }
  }
  Child.prototype=newParent();
  varchild=newChild("张");
  child.saySomeThing();
  child.sayParent();

以上就关于扣丁学堂JavaScript实现面向对象继承方式的详细介绍,希望对大家有所帮助,最后想要了解更多内容的小伙伴可以登录扣丁学堂官网咨询。扣丁学堂不仅有专业的老师和与时俱进的课程体系,还有大量的Java视频教程供学员观看学习,想要快速学习Java开发技术的小伙伴快快行动吧。

扣丁学堂微信公众号



【关注微信公众号获取更多学习资料】



查看更多关于“Java开发资讯”的相关文章>>

标签: Java培训 Java开发程序员 Java视频教程

热门专区

暂无热门资讯

课程推荐

微信
微博
15311698296

全国免费咨询热线

邮箱:codingke@1000phone.com

官方群:148715490

北京千锋互联科技有限公司版权所有   北京市海淀区宝盛北里西区28号中关村智诚科创大厦4层
京ICP备12003911号-6   Copyright © 2013 - 2019

京公网安备 11010802030908号