使用js模拟面向对象继承:先上最终的代码
function Person(name, age) {
this.name = name
this.age = age
}
Person.prototype.getName = function () {
return this.name
}
Person.prototype.getAge = function () {
return this.age
}
function Teacher(name, age, subject) {
Person.call(this, name, age)
this.subject = subject
}
// 继承方法的最终方案:
// ES6 之前抛弃默认的 Teacher.prototype
// Teacher.prototype = Object.create(Person.prototype)
//ES6 开始直接修改现有的 Teacher.prototype
Object.setPrototypeOf(Teacher.prototype, Person.prototype)
Teacher.prototype.constructor = Teacher
console.log(Teacher.prototype)
let teac = new Teacher('zs', 18, 'gaoshu')
console.log(teac.getName())
console.log(teac.constructor)
1. 先创建一个Person函数
function Person(name, age) {
this.name = name
this.age = age
}
2. 完善Person.prototype的方法
Person.prototype.getName = function () {
return this.name
}
Person.prototype.getAge = function () {
return this.age
}
3. 使用new来新建teac对象
let teac = new Teacher('zs', 18, 'gaoshu')
4. 此时teac只有Peoron函数的属性,并没有继承Person.prototype的方法,所以需要继承方法,方法二选一,后者性能略微好一些
// ES6 之前会抛弃默认的 Teacher.prototype
Teacher.prototype = Object.create(Person.prototype)
//ES6 开始直接修改现有的 Teacher.prototype
Object.setPrototypeOf(Teacher.prototype, Person.prototype)
5. 此时虽然继承了方法,但是Teacher.prototype.constructor的值是Person,想一下为什么?所以我们来修复它
Teacher.prototype.constructor = Teacher
- 以上