记录下class中的原型,实例,super之间的关系,希望能够帮到大家!记录下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
//父类
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 + ")";
}
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 topstudy
1、构造器中的this指向实例对象,在构造函数上定义的属性和方法相当于定义在类实例上的,而不是原型对象上2、toString方法是挂载到原型上的,toString1是挂载到每个实例上的
3、this.toString.bind(this),前面的this是不确定的,取决于调用方式;
后面的this指实例对象,这行代码目的是为了固定toString方法的this为实例对象,避免函数赋值给变量时this丢失
4、super关键字用于访问和调用一个对象的父对象上的函数。
5、super作为函数使用,调用的是父类的构造函数,而其中的this指向子类自己(用父类的方法操作自己的东西)
6、super 作为对象时,在普通方法中,指向父类的原型对象(只能访问原型上的函数,无法访问属性);在静态方法中,指向父类本身(调用的是父类的静态方法或属性),但是this指向子类。
编程基础网
本文标题为:ES6中class方法及super关键字
基础教程推荐
猜你喜欢
- AJAX实现数据的增删改查操作详解【java后台】 2023-02-23
- html网页中使用希腊字母的方法 2022-09-21
- JavaScript开发简单易懂的Svelte实现原理详解 2023-08-12
- ajax异步加载图片实例分析 2022-12-18
- Ajax实现简单下拉选项效果【推荐】 2022-12-28
- 【vue】三种获取input值的写法 2023-10-08
- 使用HTML5中postMessage知识点解决Ajax中POST跨域问题 2022-10-17
- vue在install时node-sass@4.14.1 postinstall:node scripts/build.js错误解决 2023-07-09
- JavaScript函数this指向问题详解 2023-08-12
- Ajax实现关键字联想和自动补全功能及遇到坑 2023-02-23
