首页IT科技es6中的class类(ES6中class方法及super关键字)

es6中的class类(ES6中class方法及super关键字)

时间2025-05-05 20:57:13分类IT科技浏览3310
导读:ES6 class中的一些问题 记录下class中的原型,实例,super之间的关系...

ES6 class中的一些问题

记录下class中的原型          ,实例               ,super之间的关系

//父类 class Dad { constructor(x, y) { this.x = 5; this.y = 1; this.state = 789 } static x = 521 state1 = 666 say() { console.log("父类bark"); } talk = () => { console.log("父类talk"); } static speak() { console.log("父类speak"); console.log(this.state); } speak(){ console.log("父类不会speak"); } } //子类 class Child extends Dad { constructor() { super() this.x = 987 this.toString = this.toString.bind(this) } state = {} toString() { return ( + this.x + , + this.y + ); } toString1 = () => { return ( + this.x + , + this.y + ); } say = () => { super.say(); console.log("子类bark"); console.log(super.x); } talk = () => { super.talk() console.log("子类talk"); } static speak() { super.speak() console.log("子类speak"); console.log(super.x); } } console.log(new Child().x); // 输出987 console.log(new Child().y); // 输出1 new Child().say(); // 输出 父类bark 子类bark undefined new Child().talk(); // 报错 super.talk is not a function Child.speak(); // 父类speak undefined 子类speak 521

构造器中的this指向实例对象     ,在构造函数上定义的属性和方法相当于定义在类实例上的          ,而不是原型对象上

子类的toString方法是挂载到原型上的               ,toString1是挂载到每个实例上的

this.toString.bind(this)     ,前面的this是不确定的     ,取决于调用方式;

后面的this指实例对象               ,这行代码目的是为了固定toString方法的this为实例对象          ,避免函数赋值给变量时this丢失

super关键字用于访问和调用一个对象的父对象上的函数          。

super作为函数使用     ,调用的是父类的构造函数               ,而其中的this指向子类自己(用父类的方法操作自己的东西)

super 作为对象时          ,在普通方法中,指向父类的原型对象(只能访问原型上的函数               ,无法访问属性);在静态方法中               ,指向父类本身(调用的是父类的静态方法或属性),但是this指向子类               。

创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!

展开全文READ MORE
查找网页关键词(关键词网页数据分析工具)