【问题标题】:Accessing protected method from other instance with same parent class in typescript从打字稿中具有相同父类的其他实例访问受保护的方法
【发布时间】:2020-07-01 12:42:10
【问题描述】:

我正在将代码从 PHP 移植到 NodeJs (Typescript)。 我遇到了以下PHP代码(简化)

<?php
class A {
    protected function protectedData() {
        return 'accessible';
    }
}
class B extends A {
    public function extractTest($anInstanceOfA) {
        return $anInstanceOfA->protectedData();
    }
}
$instanceA = new A();
$instanceB = new B();
echo $instanceB->extractTest($instanceA);

在沙箱中运行它会导致回显“可访问”。

我在 Typescript 中编写了相同的代码,但这似乎不起作用...

class A {
  protected protectedData(): string {
    return 'accessible';
  }
}

class B extends A {
  public extractTest(anInstanceOfA: A): string {
    return anInstanceOfA.protectedData();
  }
}

const instanceA = new A();
const instanceB = new B();


console.log(instanceB.extractTest(instanceA));

           

错误:属性“protectedData”受保护,只能通过“B”类的实例访问。(2446)

有没有办法在 Typescript 中实现这一点,或者 PHP 和 Typescript 中的受保护方法之间是否存在很大差异?

【问题讨论】:

    标签: typescript oop protected


    【解决方案1】:

    来自docs

    protected 修饰符的作用与 private 修饰符非常相似,但声明为 protected 的成员也可以在派生类中访问

    在上述情况下,您使用protectedData 作为函数参数anInstanceOfA 的方法,它恰好是基本类型A。但是你不能通过this.protectedData() 访问protectedData within 派生类B,所以 TS 在这里大喊大叫。哪些有效,哪些无效:

    class B extends A {
      public extractTest(anInstanceOfA: A, instanceOfB: B): string {
        anInstanceOfA.protectedData() // ✖, protected member of arg with base class 
        instanceOfB.protectedData() // ✔, protected member of arg with *same* class 
        this.protectedData(); // ✔, (derived) protected member via `this`
        return anInstanceOfA["protectedData"]() // escape-hatch with dynamic property access
      }
    }
    

    因此,您既可以将protectedData 声明为public,也可以使用escape-hatch,这将使protected 成员可以通过使用括号表示法的动态属性访问来访问。

    anInstanceOfA["protectedData"]()
    

    Playground sample to try it out

    【讨论】:

      猜你喜欢
      • 2020-05-02
      • 2013-04-06
      • 2011-03-11
      • 1970-01-01
      • 2011-12-20
      • 2016-04-04
      • 2020-11-25
      • 1970-01-01
      • 2016-05-06
      相关资源
      最近更新 更多