js如何实现继承
方法一:使用原型
function Animal(legsNumber){
this.legsNumber = legsNumber
}
Animal.prototype.kind = "动物"
function Dog(name){
this.name = name
Animal.call(this,4)
}
Dog.prototype.__proto__ = Animal.prototype//被ban了
Dog.prototype.kind = "狗"
Dog.prototype.say = (){
console.log(`我是${this.name},我有${this.legsNumber}条腿`)
}
const dog = new Dog
注意,上面的被ban了的那一句可以换成
var f = function (){}
f.prototype = Animal.prototype
Dog.prototype = new f()
方法二:用class
class Animal {
constructor(legsNumber){
this.legsNumber = legsNumber
}
run(){}
}
class Dog extends Animal {
consturctor(name){
super(4)
this.name = name
}
say(){
console.log(`我是${this.name},我有${this.legsNumber}条腿`)
}
}