【问题标题】:How to reference a static parameter from subclass at a super class static function?如何在超类静态函数中从子类引用静态参数?
【发布时间】:2019-06-30 01:32:02
【问题描述】:

我有以下代码:

class A {
    static printName = () => {
        console.log(this.name);
    }
}

class B extends A {}

A.printName(); //Prints 'A'
B.printName(); //Prints 'A' (I thought it would print 'B')

为什么B.printName() 不打印“B”而不是“A”?

【问题讨论】:

    标签: javascript inheritance ecmascript-6 static


    【解决方案1】:

    使其成为普通函数,而不是箭头函数 - 箭头函数失去与 this 的绑定:

    class A {
        static printName() {
            console.log(this.name);
        }
    }
    
    class B extends A {}
    
    A.printName();
    B.printName();

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-01
      • 2011-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-14
      • 1970-01-01
      相关资源
      最近更新 更多