JS实现面向对象继承的5种方式分析

2019-11-16,,,,

本文实例讲述了JS实现面向对象继承的5种方式。分享给大家供大家参考,具体如下:

js是门灵活的语言,实现一种功能往往有多种做法,ECMAScript没有明确的继承机制,而是通过模仿实现的,根据js语言的本身的特性,js实现继承有以下通用的几种方式

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

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

function Parent(firstname)
{
  this.fname=firstname;
  this.age=40;
  this.sayAge=function()
  {
    console.log(this.age);
  }
}
function Child(firstname)
{
  this.parent=Parent;
  this.parent(firstname);
  delete this.parent;
  this.saySomeThing=function()
  {
    console.log(this.fname);
    this.sayAge();
  }
}
var mychild=new Child("李");
mychild.saySomeThing();

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

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

function Parent(firstname)
{
  this.fname=firstname;
  this.age=40;
  this.sayAge=function()
  {
    console.log(this.age);
  }
}
function Child(firstname)
{
  this.saySomeThing=function()
  {
    console.log(this.fname);
    this.sayAge();
  }
  this.getName=function()
  {
    return firstname;
  }
}
var child=new Child("张");
Parent.call(child,child.getName());
child.saySomeThing();

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

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

function Parent(firstname)
{
  this.fname=firstname;
  this.age=40;
  this.sayAge=function()
  {
    console.log(this.age);
  }
}
function Child(firstname)
{
  this.saySomeThing=function()
  {
    console.log(this.fname);
    this.sayAge();
  }
  this.getName=function()
  {
    return firstname;
  }
}
var child=new Child("张");
Parent.apply(child,[child.getName()]);
child.saySomeThing();

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

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

function Parent()
{
  this.sayAge=function()
  {
    console.log(this.age);
  }
}
function Child(firstname)
{
  this.fname=firstname;
  this.age=40;
  this.saySomeThing=function()
  {
    console.log(this.fname);
    this.sayAge();
  }
}
Child.prototype=new Parent();
var child=new Child("张");
child.saySomeThing();

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

function Parent()
{
  this.sayAge=function()
  {
    console.log(this.age);
  }
}
Parent.prototype.sayParent=function()
{
  alert("this is parentmethod!!!");
}
function Child(firstname)
{
  Parent.call(this);
  this.fname=firstname;
  this.age=40;
  this.saySomeThing=function()
  {
    console.log(this.fname);
    this.sayAge();
  }
}
Child.prototype=new Parent();
var child=new Child("张");
child.saySomeThing();
child.sayParent();

更多关于JavaScript相关内容感兴趣的读者可查看本站专题:《javascript面向对象入门教程》、《JavaScript错误与调试技巧总结》、《JavaScript数据结构与算法技巧总结》、《JavaScript遍历算法与技巧总结》及《JavaScript数学运算用法总结》

希望本文所述对大家JavaScript程序设计有所帮助。

您可能感兴趣的文章:

  • javascript面向对象创建对象的方式小结
  • javascript面向对象三大特征之多态实例详解
  • javascript面向对象三大特征之继承实例详解
  • javascript面向对象三大特征之封装实例详解
  • JavaScript面向对象中接口实现方法详解
  • 浅谈JavaScript面向对象--继承
  • JavaScript碎片—函数闭包(模拟面向对象)
  • JS面向对象基础讲解(工厂模式、构造函数模式、原型模式、混合模式、动态原型模式)
  • JS面向对象编程详解
  • JS 面向对象之神奇的prototype
  • javascript面向对象程序设计实践常用知识点总结

《JS实现面向对象继承的5种方式分析.doc》

下载本文的Word格式文档,以方便收藏与打印。