原型式继承
function Person(name) {
this.name = name
}
Person.prototype.sayHi=function(){console.log("Hi,My name is " + this.name)}
function Teacher(name, subject) {
Person.call(this, name)
this.subject = subject
}
Teacher.prototype = Object.create(Person.prototype);
Teacher.prototype.sayHi=function(){console.log("Hi,I'm " + this.name)}
Teacher.prototype.constructor = Teacher;
let p = new Person("Tony")
p.sayHi()
let t = new Teacher("Mike")
t.sayHi()
要点
如果子构造函数prototype上有和父构造函数prototype中的同名方法,子构造函数的方法会覆盖父构造函数的
Teacher.prototype = Object.create(Person.prototype)
这句代码使得 Teacher.prototype.__proto__=== Person.prototype
同时丢失了Teacher.prototype中的constructor属性Teacher.prototype.constructor = Teacher
这句代码可以使丢失的constructor属性再次出现
类继承
class Person {
constructor(name) {
this.name = name
}
sayHi = () => {
console.log("Hi,My name is " + this.name)
}
}
class Teacher extends Person {
constructor(name, subject) {
super(name)
this.subject = subject
}
sayHi = () => {
console.log("Hi,I'm " + this.name)
}
}
let p = new Person("Tony")
p.sayHi()
let t = new Teacher("Mike")
t.sayHi()