在之前的博文【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;
};