温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

JS怎么实现面向对象继承

发布时间:2021-04-20 11:03:55 来源:亿速云 阅读:178 作者:小新 栏目:web开发

这篇文章给大家分享的是有关JS怎么实现面向对象继承的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

JS是什么

JS是JavaScript的简称,它是一种直译式的脚本语言,其解释器被称为JavaScript引擎,是浏览器的一部分,主要用于web的开发,可以给网站添加各种各样的动态效果,让网页更加美观。

本文实例讲述了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();

感谢各位的阅读!关于“JS怎么实现面向对象继承”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

js
AI