关于super指向性的问题

来源:4-3 简单的多态

LeslieChan994

2020-03-05 13:27:10

 class A {
  constructor() {
    this.x = 1;
  }
}

class B extends A {
  constructor() {
    super();
    this.x = 2;
    super.x = 3;
    console.log(super.x); // undefined
    console.log(this.x); // 3
  }
}

let b = new B();

如图,请问怎么理解这三行的super指向?

super.x = 3;

console.log(super.x); // undefined

   console.log(this.x); // 3

写回答

2回答

好帮手慕星星

2020-03-05

同学你好,老师前面说过了,super.x这种写法就是错误的,继承来的属性应该用this.x输出。所以结果是undefined 。

祝学习愉快!

0

好帮手慕星星

2020-03-05

同学你好,super.x=3这种写法就是是不对的,constructor中用来继承父类中属性的,直接写super()以及使用this定义子类中的属性。继承来的属性在子类中使用的时候用this来获取就好。

如果想要调用父类中的方法,可以这样写

http://img.mukewang.com/climg/5e60bec8099ad05705390548.jpg

如果我的回答帮到了你,欢迎采纳,祝学习愉快~

0
heslieChan994
h 我是想问console.log(super.x); // undefined 为什么输出undefined,不应该是1或者3么?
h020-03-05
共1条回复

0 学习 · 10739 问题

查看课程