// js基于原形链的继承
function Persion(name,age){
this.name=name
this.age= age
this.walk = function(){
console.log(${this.name}正在行走
)
}
}
Persion.prototype.hi = function(){
console.log(你好,我的名字是${this.name},我今年${this.age} 岁了
)
}
function Student(name,age,className){
Persion.call(this,name,age);
this.className = className
// 子类中的方法
this.xiezuoye = function(){
console.log(${this.className}的${this.name}正在写作业
)
}
// 覆盖父类中的方法
this.hi = function(){
console.log(你好 ,我的名字是${this.name},我今年${this.age}岁了,我的班级是${this.className}
)
}
}
// 将 Student 的 prototype 属性 设置为一个空对象 对象的 prototype 属性指向 Persion 的 prototype 属性
// 实现了继承Persion Object.create创建一个空对象
Student.prototype = Object.create(Persion.prototype)
// 为了保持一致性 设置prototype 的 constructor 属性为 Student 如果不设置将指向 Persion
Student.prototype.constructor = Student
// 添加子类 Student 中 自己的 方法
Student.prototype.dushu = function(){
console.log(${this.className}的${this.name}正在用功读书
)
}
// ------ 测试 -------
let per = new Persion(‘张三’,23)
per.walk()
per.hi()
let stu = new Student(‘李四’,24,‘高三一班’)
stu.hi()
stu.dushu()
stu.xiezuoye()
class Persion{
constructor(name,age,height=176,tizhong =77){
this.name = name
this.age = age
this.state={
height:height,
tizhong:tizhong,
}
}
hi(){
console.log(你好,我的名字是${this.name},我今年,${this.age}岁了
)
}
walk(){
console.log(${this.name}正在行走
)
}
toString(){
console.log(你好,我的名字是${this.name},我今年${this.age}岁了,我的身高是${this.state.height},我的体重是${this.state.tizhong}
)
}
}
// 继承 persion
class Student extends Persion{
constructor(name,age,height,tizhong,classname){
super(name,age,height,tizhong)
this.classname = classname
}
// 重写hi方法
hi(){
console.log(“你好 ,我是” +this.classname + ‘的’+ this.name + ’ , 我今年 ’ + this.age + ‘岁了’ )
}
}
/// --------- 测试 ---------
let stu = new Student(“maoyl”,24,188,89,‘高三一班’)
stu.hi()
stu.walk()
stu.toString()