欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 养生 > ES6入门---第三单元 模块一:类、继承

ES6入门---第三单元 模块一:类、继承

2025/5/7 8:25:47 来源:https://blog.csdn.net/qq_41775119/article/details/81782078  浏览:    关键词:ES6入门---第三单元 模块一:类、继承

补充:

prototype 属性使您有能力向对象添加属性和方法。

object.prototype.name=value

 <script>function Person(name, age){this.name = name;this.age = age;}/* Person.prototype.showName = function(){return `名字为: ${this.name}`;};Person.prototype.showAge = function(){return `年龄为: ${this.age}`;}; */
//新旧版对比Object.assign(Person.prototype,{ //assign 合并showName(){return `名字为: ${this.name}`;},showAge(){return `年龄为: ${this.age}`;}});let p1 = new Person('Strive', 18);console.log(p1.showName());console.log(p1.showAge());</script>

【ES6】类:ES6里面class没有提升功能,在ES5,用函数模拟可以,默认函数提升

补充:

constructor 属性返回对创建此对象的数组函数的引用。

object.constructor
 class Person{//首字母大写!!!//类:constructor(name,age){ //构造方法(函数), 调用new时自动执行//console.log(`构造函数执行了, ${name}, ${age}`);this.name = name;this.age = age;}showName(){return `名字为: ${this.name}`;}showAge(){return `年龄: ${this.age}`;}}let p1 = new Person('Strive', 18);console.log(p1.showName(), p1.showAge());

快捷定义函数: 省打麻烦字

let a = 'strive';let b = 'method';class Person{[a+b](){}}

 this很难出错,若出错:矫正函数

    1. fn.call(this指向谁, args1, args2....)
    2. fn.apply(this指向谁, [args1, args2....])
    3. fn.bind()

【get set】class里面取值函数(getter), 存值函数(setter)

例:

 class Person{constructor(){}get aaa(){return `aaa的属性`;}set aaa(val){console.log(`设置aaa属性,值为:${val}`);}}let p1 = new Person();p1.aaa='123';console.log(p1.aaa);

【静态方法】: 就是类身上方法 可以直接类名调用 不用重新创建json
    static aaa(){

    }

    父类.aaa();

 继承:

【老方法】

  //父类function Person(name){this.name = name;}Person.prototype.showName = function(){return `名字是: ${this.name}`;};//子类function Student(name,skill){Person.call(this,name); //继承属性  //使用矫正this函数this.skill = skill;}Student.prototype = new Person(); //继承方法//调用let stu1 = new Student('Strive','逃学');console.log(stu1.showName());

【新】

  //父类class Person{constructor(name){this.name = name;}showName(){return `名字为: ${this.name}`;}}//子类class Student extends Person{constructor(name,skill){//别忘了加上参数super(name);//想写子类自己的构造函数必须super()把父类construct函数拉过来 this.skill = skill;}showSkill(){return  `哥们儿的技能为: ${this.skill}`;}}//调用let stu1 = new Student('Strive','逃学');console.log(stu1.showSkill());

*子类父类都有同一函数名的函数 怎么办??

【补充】调用父级里函数 格式:super.函数名()

例:

//子类class Student extends Person{constructor(name,skill){super(name);this.skill = skill;}showName(){super.showName(); //先父级的方法执行//TODO 可以加做子级事情的其他了console.log('子类里的showName');}showSkill(){return  `哥们儿的技能为: ${this.skill}`;}}

在父级函数基础上加上子级自己的函数!

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词