javascript prototype inheritance and succession contrast class extends

// parent class Animal
function Animal(name) {
this.name = name;
this.sleep = function () {
console.log (this.name + 'is sleeping!')
}
}
 
// cat is a subclass of Animal
function Cat(name,age) {
Animal.call(this,name);
// subclass Cat newly added members age eat ()
Cat.prototype.age = age;
Cat.prototype.eat = function () {
console.log (this.name + 'is cat' + 'is eating' + 'my age is' + this.age)
}
}

 

// --------------------- --------- calling code
var animal_obj = new Animal ( 'animals');
animal_obj.sleep();
 
var cat_obj = new Cat('猫',10);
cat_obj.sleep();
cat_obj.eat();
 
 
 
//-------------------------------------------------------class------------------------------------------------------------------
// parent class Animal
class Animal {
constructor(name) {
this.name = name;
}
sleep(){
console.log (this.name + 'is sleeping!')
}
}


// cat is a subclass of Animal
class Cat extends Animal {
//Constructor
constructor(name, age) {
super (name); // super call the parent class constructor is selected from
this.age = age; // add properties subclass members age
}
// add properties subclass members eat (), class member functions defined not need to use this., They do not function
eat() {
console.log (this.name + 'is cat' + 'is eating' + 'my age is' + this.age)
}
}

// --------------------- --------- calling code
var animal_obj = new Animal ( 'animals');
animal_obj.sleep();

var cat_obj = new Cat('猫', 10);
cat_obj.sleep();
cat_obj.eat();
// -------------------------- ------- run exactly the same result
 
 

Guess you like

Origin www.cnblogs.com/qinlongqiang/p/11495211.html