前言
JS作为面向对象的弱类型语言,继承也是其非常强大的特性之一。那么如何在JS中实现继承呢?让我们拭目以待。
既然要实现继承,那么首先我们得有一个父类,代码如下:
//定义一个动物类
functionAnimal (name) {//属性
this.name = name || 'Animal';//实例方法
this.sleep = function(){
console.log(this.name + '正在睡觉!');
}
}//原型方法
Animal.prototype.eat = function(food) {
console.log(this.name + '正在吃:' +food);
};
1、原型链继承
核心: 将父类的实例作为子类的原型
functionCat(){
}
Cat.prototype= newAnimal();
Cat.prototype.name= 'cat';//Test Code
var cat = newCat();
console.log(cat.name);
console.log(cat.eat('fish'));
console.log(cat.sleep());
console.log(catinstanceof Animal); //true
console.log(cat instanceof Cat); //