javascript继承的实现方式

本文介绍了JavaScript中的几种继承方式,包括使用原型(Prototype)、call及apply方法实现继承,并展示了superClass的使用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

随便写写,具体的就不再做过多啰嗦了

1、原型(Prototype),建议自己研究原型与闭包

var Person = function(){   
    this.name = "liyatang";
};
Person.prototype = {
    //可以在这里提供Person的基本功能
    getName : function(){
        return this.name;
    }
}

注:Prototype是私有的,在继承关系中需要将父类对象添加到子类的原型

2、call,applay的使用法

function Animal(name) {
    this.name = name;
    this.showName = function() {
        console.log(this.name);
    };
}

function Cat(name) {
    Animal.call(this, name);
}
<pre name="code" class="javascript">
function Dog(name) {
    Animal.apply(this, name);
}

var cat = new Cat("Black Cat"); //call必须是object

var dog = new Dog(["Black Dog"]); //apply必须是array

cat.showName();
dog.showName();

console.log(cat instanceof Animal);
console.log(dog instanceof Animal);

 3、superClass的使用

function Animal(name) {
    this.name = name;
    this.showName = function() {
        alert(this.name);
    };
};

function Cat(name) {
    this.superClass = Animal;
    this.superClass(name);
    delete superClass;
}

var cat = new Cat("Black Cat");

cat.showName();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值