说一下类的创建和继承
/* 定义一个动物类 */
function Animal (name) {
/* 属性 */
this.name = name || 'Animal';
/* 实例方法 */
this.sleep = function(){
console.log(this.name + '正在睡觉!');
}
}
/* 原型方法 */
Animal.prototype.eat = function(food) {
console.log(this.name + '正在吃:' + food);
};
这样就生成了一个Animal类,实例化对象后,有方法和属性。
function Cat(){ }
Cat.prototype = new Animal(); /* 原型继承 */
Cat.prototype.name = 'cat';
var cat = new Cat();
介绍:
将超类的实例当作子类的原型,形成一条原型链,访问子类上不存在的方法时,就可以通过这条原型链来寻找。
可以解决的问题:
遗留的问题:
function Cat(name){
Animal.call(this); /* 构造继承 */
this.name = name || 'Tom';
}
var cat = new Cat();
介绍:
在实例化子类对象的内部,以子类的名义(call)调用超类构造函数,来实现对超类的属性的继承。
可以解决的问题:
遗留的问题:
function Cat(name){
Animal.call(this); /* 第二次调用 Animal */
this.name = name || 'Tom';
}
Cat.prototype = new Animal(); /* 第一次调用 Animal */
Cat.prototype.constructor = Cat;
var cat = new Cat();
介绍:
结合构造继承和原型继承,将二者的优势相结合。
可以解决的问题:
遗留的问题:
// 圣杯继承(添加一个中间函数,由中间函数继承原型链)
function object(o){
function F(){};
F.prototype = o;
return new F();
}
/* ------------- 寄生组合继承核心 ----------------- */
function inheritPrototype(subType, superType){
let prototype = object(superType.protoType); /* 创建一个继承了“父类原型”的对象,将其作为子类的原型 */
subType.prototype = prototype;
prototype.constructor = subType; /* 完善原型链 */
}
/* -------------------------------------------------- */
Animal.prototype.sayName = function(){
console.log(this.name);
}
function Cat(name){
Animal.call(this);
this.name = name || 'Tom';
}
inheritPrototype(Cat, Animal); /* 寄生组合继承 */
var cat = new Cat();
该方法就是在组合继承的基础上,对组合继承遗留的问题进行优化。