js基于原形链的继承 与class 继承

// 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()
在这里插入图片描述

原文链接 http://www.maoyl.top/#/articledetails/24

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值