1.基于原型的继承
子对象继承父对象属性或方法,需要将子对象的prototype
等于父对象构造函数的实例
function Parent(name, age) {
this.name = name;
this.age = age;
this.sayHi = function () {
console.log("Hi");
}
}
function Child(name, age) {
this.name = name;
this.age = age;
}
Child.prototype = new Parent()
const child = new Child()
child.sayHi() //Hi
2.基于class的继承
类的继承用到extends
,内部通过super()
继承需要的属性
class Parent {
constructor(name) {
this.name = name
}
sayHi() {
console.log("Hi");
}
}
class Child extends Parent {
constructor(name) {
super(name)
}
}
const child = new Child("frank")
console.log(child.name); //frank
child.sayHi() //Hi
网友评论