JavaScript继承篇

作为一门面向对象的语言,JavaScript并没有“父类”与“子类”的概念,也没有像java提供extends关键字,c++中直接提供继承方法等那样直接进行继承。然而继承在面向对象的语言中的重要性不言而喻,所以,下述将简要探讨一下,JavaScript中的几种常用的继承方法。

首先,我们需要定义一个父类:

function Parent(username)
{
    this.username = username;
    this.sayHello = function()
    {
        return this.username;
    }
}

没有现成的继承方法的情况下,JavaScript学习者们通过对JavaScript的理解总结出5中常见的实用的继承方法:

  • 对象冒充
  • call方法
  • apply方法
  • 原型链方式
  • 混合方式(推荐)

1、对象冒充
顾名思义,子类通过冒充父类,从而获得父类的属性和方法,其中最重要的是下列三行代码

this.method = Parent;
this.method (username);
delete this.method;

以上的this均指代的是“子代”的实例,第一行代码为定义一个成员方法,即把函数Parent作为“子代”的成员方法;第二行为执行成员方法,该方法把Parent的属性和方法添加给了“子代”的实例;第三行为删除该方法,因为方法已经执行,“父代”的属性与方法已经获得。删不删都一样。

function Child(username,password)
{
    this.method = Parent;
    this.method(username);
    delete this.method;

    this.password = password;
    this.sayWorld = function()
    {
        return this.password;
    }
}
var parent = new Parent("zhangsan");
var child = new Child("lisi","123");

2、call方法方式
call方法是Function对象中的方法,因此我们定义的每个函数都有该方法。可以通过调用函数名来调用call方法call方法的第1个参数会被传递给Parent函数中的this,从第2个参数开始,逐一赋值给Parent函数中的参数。

function Child(username,password)
{
    Parent.call(this,username);
    
    this.password = password;
    this.sayWorld = function()
    {
        return this.password;
    }
}
var parent = new Parent("zhangsan");
var child = new Child("lisi","123");

Parent.call(this,username) 此处的this为子对象的this,传递给父对象,则function Parent(username)中的this全部为子对象的this,即完成了继承。
3、apply方式方法
apply方式与call方法结构上相近,唯一的区别就是apply中的参数传递规定的是数组形式,不用像call方法那样一个一个地写。

function Child(username,password)
{
    Parent.apply(this,new Array(username));
    
    this.password = password;
    this.sayWorld = function()
    {
        return this.password;
    }
}

4、原型链方式
原型链方式与对象冒充的原理一样,通过将Parent函数赋给“子代”作为其成员方法从而实现继承。然而,单纯的原型链方式有其固有的缺陷,与使用原型链方式构建对象时一样,它无法给构造函数传递参数。

function Parent()
{}
Parent.prototype.username = "zhangsan";
Parent.prototype.sayHello = function()
{
    return this.username;
}

function Child()
{}
Child.prototype = new Parent();
Child.prototype.password = "123";
Child.prototype.sayWorld = function()
{
    return this.password;
}

var child = new Child();
child.sayHello();
child.sayWorld();

5、混合方式
Parent.call()进行属性的继承,Child.prototype=new Parent()进行方法的继承。实现方法共享,属性私有。

function Parent(username)
{
    this.username=username;
}
Parent.prototype.sayHello = function()
{
    return this.username;
}

function Child(username,password)
{
    Parent.call(this,username);

    this.password = password;
}
Child.prototype = new Parent();
Child.prototype.sayWorld = function()
{
    return this.password;
}

var child=new Child("zhangsan","123");
child.sayHello();
child.sayWorld();
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值