【Javascript】利用原型和原型链来实现类(函数)之间的继承

本文深入探讨JavaScript中的继承机制,通过实例展示如何使用原型和原型链实现类之间的继承,包括子类如何调用父类的公共函数及成员。

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

在之前的博文【Javascript】原型和原型链的深层解析中,我们已经探究了原型和原型链之间的关系。当时探究完之后,感觉不到探究他的意义是什么。那么现在,我们来用原型和原型链来实现一下类(也是方法)之间的继承。
我们都知道,在java中,有些类与类之间会存在继承关系,继承的存在,使得编写代码非常的方便。同样为了使得编程的方便,在javaScript里面,我们也实现类与类的继承关系。
继承的特性包括:子类可以调用父类的public函数,子类拥有父类的public成员;
首先先定义一个类(函数)

function Animal (name) {
	this.name = (name ? name : "匿名");
	this.cry = function () {
		return "哺乳动物" + name + "在叫.";
	}
};
Animal.prototype.count = 0;

function Dog (name, type) {
	this.name = (name ? name : "匿名");
	this.type = (type ? type : "未知品种");
	this.cry = function () {
		return type + name + "在汪汪。";
	}
};
Dog.prototype.dog = "dog";

function Dogie (name, type, owner) {
	this.name = (name ? name : "匿名");
	this.type = (type ? type : "未知品种");
	this.owner = owner;
	this.cry = function () {
		return owner + "家的" + type + name + "在汪汪。";
	}
};
Dogie.prototype.dogie = "dogie";

上述三个类,之间确实有一定的关系,Animal类只有一个参数name,Dog有两个参数name和type,Dogie有三个参数name、type和owner 。可以看出,这三个类之间按理说应该存在继承关系,我们先把他们依次输出,看看情况。

var animal = new Animal("狗");
var dog = new Dog("狗", "哈巴");
var dogie = new Dogie("狗", "哈巴", "小白");
console.log("animal:", animal);
console.log("dog:", dog);
console.log("dogie:", dogie);

执行结果:
在这里插入图片描述由上述结果可知,dogie和dog的__proto__,他们指向的都不是各自的父类的构造方法。想要实现父类的继承,我们需要实现父类的构造,也就是,子类指向父类的构造方法。
现在编写一个类:

function Extends(Parent, Child) {
	if (Parent == undefined 
		|| Child == undefined
		|| Parent.prototype == undefined
		|| Child.prototype == undefined) {
		return;
	}

	var TempClass = new Function;
	TempClass.prototype = Parent.prototype;
	var tmp = new TempClass;
	Child.prototype = tmp;
	Child.prototype.constructor = Child;
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值