当前位置: 移动技术网 > IT编程>开发语言>JavaScript > JS实现面向对象继承的5种方式分析

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

2018年08月10日  | 移动技术网IT编程  | 我要评论

本文实例讲述了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程序设计有所帮助。

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

相关文章:

验证码:
移动技术网