<script>
// ES5
function Person(name,age) {
this.name = name
this.age = age
}
Person.prototype.speak = function() {
console.log(this.name + " 会说话")
}
function Student(name,age,student) {}
// 原型继承
Student.prototype = new Person()
let s1 = new Student("小明",10,"学生")
s1.speak()
console.log(s1)
Student.prototype = new Person("小明",10)
s1 = new Student()
s1.speak()
console.log(s1)
Student.prototype = new Person("小明",10)
s1 = new Student("大明",18,"学生")
s1.speak()
console.log(s1)
/*
Person:父类,Student:子类
原型继承总结:
1. 子类实例化传的参数无效
2. 继承的方法可用
3. 有效传参必须在 new 的父类中
*/
// 冒充继承
function Teacher(name,age,teacher) {
Person.call(this,name,age)
this.teacher = teacher
}
let t1 = new Teacher("tony",26,"英语老师")
console.log(t1)
try {
t1.speak()
} catch (error) {
console.log(error)
}
/*
冒充继承总结:
1. 冒充继承的原型为Object
2. 无法使用 call,apply 指向的类的方法
*/
// 混合继承 = 冒充继承 + 原型继承
Teacher.prototype = new Person()
let t2 = new Teacher("lihua",30,"数学老师")
console.log(t2)
t2.speak()
/*
混合继承总结:
1. 获取了 call,apply 指向的类的方法,并将这个类作为原型
2. 传参在 new 的子类中,符合我们的编程习惯
*/
</script>
ES5,js 基础继承的三种方式
最新推荐文章于 2024-09-02 17:34:07 发布