class Animal {
constructor () {
this.name = name;
}
}
类的声明
function Animal () {
this.name = "Jack"
}
ES6中的class的声明
class Animal2 {
constructor (){
this.name = name
}
}
JS继承的实现方式
//定义一个动物类
function Animal (name) {
//属性
this.name = name || "Animal"
//实例方法
this.sleep = function () {
console.log(this.name )
}
}
//原型方法
Animal.prototype.eat = function (food) {
console.log(this.name +food);
};
1 原型链继承
核心:将父类的实例作为子类的原型
function Cat(){
}
Cat.prototype = new Animal();
Cat.prototype.name = 'cat'
var cat = new Cat();
console.log(cat.name)
console.log(cat.sleep())
2 构造继承
核心:使用父类的构造函数来增强子类实例,等于是复制父类的实例属性给子类(没有用到原型)
function Cat(name) {
Animal.call(this);
this.name = name || "Tom";
}
var cat = new Cat();
console.log(cat.name)
console.log(cat.sleep())
console.log(cat instanceof Animal); //false
console.log(cat instanceof Cat); //true
注意:不能继承构造函数中原型对象中的方法和属性
3 实例继承
function Cat(name) {
var instance = new Animal()
instacne.name = name || "Tom";
return instance
}
var cat = new Cat()
console.log(cat instanceof Animal) //true
console.log(cat instanceof Cat) //false
4 拷贝继承
function Cat(name) {
var animal = new Animal();
for( var p in animal ) {
Cat.prototype[p] = animal[p];
}
Cat.prototype.name = name || "Tom';
}
var cat = new Cat();
console.log(cat.name)
console.log(cat instanceof Animal); //false
console.log(cat instanceof Cat) ; //true