怎么在 js 中如何实现继承

来源:互联网转载和整理 2024-05-15 11:48:56

js继承


可用以下两种方法实现继承

class/extends

classAnimal{
constructor(name){
this.name=name
}

hello(){
console.log('hello')
}
}

classDogextendsAnimal{
constructor(name,say){
super(name)
this.say=say
}
}

function/new

functionAnimal(name){
this.name=name
}

Animal.prototype.hello=()=>{
console.log('hello')
}

functionDog(name,say){
//01 继承属性
Animal.call(this,name)
this.say=say
}

//02 通过连接原型链完成继承
Dog.prototype=Object.create(Animal.prototype)

//03 再加上constructor
Dog.prototype.constructor=Dog
//Reflect.defineProperty(Dog.prototype,"constructor",{
//value:Dog,
//enumerable:false,//不可枚举
//writable:true
//})