javascript之继承
作者:互联网
ES6语法实现
class Animal {
constructor(type, color) {
this.type = type
this.color = color
}
speak(word) {
console.log(this.type + " says " + word)
}
colorIs() {
console.log(`${this.type} is ${this.color}`)//ES6新的字符串拼接方式
}
}
class Cat extends Animal {
constructor(color) {
super()
this.type = "cat"
this.color = color
}
speak() {
console.log("cat says miao")
}
eat() {
console.log("eat rats")
}
}
let kitty = new Cat("yellow")
kitty.speak()
kitty.speak("mew")//js没有函数重载,子类的speak()会将父类的speak(word)覆盖
kitty.eat()
kitty.colorIs()
输出:
cat says miao
cat says miao
eat rats
cat is yellow
ES5原型链继承与构造器继承
var Animal = function (type, color) {
this.color = color;
this.type = type;
this.say = function () {
console.log(`I am a ${this.color} ${this.type}`);
}
}
var dog = new Animal("dog", "yellow");
dog.say();
var Cat = function (color) {
this.color = color;
this.type = 'cat';
this.eat = function () {
console.log(`${this.color} ${this.type} eats rat`);
}
}
Cat.prototype = new Animal();
var kitty = new Cat('pink');
kitty.say();
kitty.eat();
var Human = function (type) {
Animal.call(this, type, 'smart');
this.make = () => {
console.log(`${this.type} makes tools`);
}
}
var liMing = new Human('Chinese');
liMing.say();
liMing.make();
输出:
I am a yellow dog
I am a pink cat
pink cat eats rat
I am a smart Chinese
Chinese makes tools
标签:console,log,继承,javascript,kitty,cat,color,type 来源: https://www.cnblogs.com/Minstrel223/p/12383377.html