继承 2022年3月7日
继承
面向对象 ES5
function Person(){
this.username = 'jack'
}
//原型对象 -- 公共的属性和方法
Person.prototype.say =funciton(){
}
ES6
class Person{
}
new Person()
面向对象特性
封装性
多态性
一个事物有多种表现形式
let a =100
let a = '100'
继承性
子类继承父类,子类就有父类的属性和方法
构造函数继承
--在子类的构造函数中调用父类的构造函数
Person.call(this)
只能继承父类函数中的属性和方法,父类原型中的无法继承
拷贝继承
--遍历父类原型对象,拷贝父类原型对象属性和方法到子类原型对象上
for(let key in Person.prototype){
Student.prototype[key] = Person.prototype[key]
}
```<script>
//人类构造函数 - 父类
function Person(name){
this.name = name
this.say = function(){
console.log(this.name,'说话');
}
}
Person.prototype.eat = function(){
console.log('吃饭');
}
//学生类 构造函数 -子类
function Student(num,name){
Person.call(this,name) //1. 构造函数继承
this.num = num
this.readbook = function(){
console.log('读书');
}
}
//拷贝继承- 原型属性和方法
for(let key in Person.prototype){
Student.prototype[key] = Person.prototype[key]
}
let s1 = new Student(1001,'jack')
s1.readbook()
s1.say()
console.log(s1.name);
s1.eat()
</script>