javascript 原型继承 与class extends 继承对比

//父类 Animal
function Animal(name) {
this.name = name;
this.sleep = function () {
console.log(this.name + '正在睡觉!')
}
}
 
//cat 是 Animal 的子类
function Cat(name,age) {
Animal.call(this,name);
//子类 Cat 新增加的 成员 age eat()
Cat.prototype.age = age;
Cat.prototype.eat = function () {
console.log(this.name + 'is cat ' + '正在吃东西'+' my age is '+ this.age)
}
}
//---------调用代码---------------------
var animal_obj = new Animal('动物');
animal_obj.sleep();
 
var cat_obj = new Cat('猫',10);
cat_obj.sleep();
cat_obj.eat();
 
 
 
//-------------------------------------------------------class------------------------------------------------------------------
//父类 Animal
class Animal {
constructor(name) {
this.name = name;
}
sleep(){
console.log(this.name + '正在睡觉!')
}
}


//cat 是 Animal 的子类
class Cat extends Animal {
//构造函数
constructor(name, age) {
super(name); //super 选调用父类构造方法
this.age = age; //子类新增属性成员 age
}
//子类新增属性成员 eat(), class定义的成员函数不须要用 this.,也不用 function
eat() {
console.log(this.name + 'is cat ' + '正在吃东西' + ' my age is ' + this.age)
}
}

//---------调用代码---------------------
var animal_obj = new Animal('动物');
animal_obj.sleep();

var cat_obj = new Cat('猫', 10);
cat_obj.sleep();
cat_obj.eat();
//-------运行结果一模一样--------------------------
 
 

猜你喜欢

转载自www.cnblogs.com/qinlongqiang/p/11495211.html