为什么错误的this.propertyName引用抽象方法实现?

时间:2016-03-29 12:23:06

标签: typescript

为什么在下面的代码中我在抽象方法实现中出错了this.name引用?

abstract class Abstract {
  protected name: string;

  constructor () {
    this.abstractMethod();
  }

  protected abstract abstractMethod (): void;
}

class Concrete extends Abstract {
  protected name: string = 'Concrete';

  protected abstractMethod () {
    console.log(this, this.name); // Concrete, undefined
  }
}

new Concrete();

Link on example

3 个答案:

答案 0 :(得分:4)

查看已编译的JavaScript可以在以下情况下提供帮助:

function Concrete() {
    _super.apply(this, arguments); // calls this.abstractMethod()
    this.name = 'Concrete';
}

在超级致电之后 - 通过调用Abstract的构造函数 - 之后才会进行作业,因此this.abstractMethod被称为this.nameundefined

答案 1 :(得分:1)

我真的不知道,你想要实现什么,但也许这会有所帮助,对不起我的英语

private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        while (serialPort1.IsOpen && serialPort1.BytesToRead != 0)
        {
            int howManyBytes = serialPort1.BytesToRead;
            byte[] newData = new byte[howManyBytes];
            serialPort1.Read(newData, 0, howManyBytes);
            bufferString.AddRange(newData);
        }
    }

控制台:

abstract class Abstract {
    protected name: string;

    constructor () {
        //this.abstractMethod();
    }

    protected abstract abstractMethod (): void;
}

class Concrete extends Abstract {
    protected name: string = 'Concrete';

    constructor () {
        super();
        this.abstractMethod();
    }

    protected abstractMethod () {
        console.log(this, this.name);
    }
}

答案 2 :(得分:1)

您观察到的现象是可预测的,因为构造函数按从基类到具体类的顺序运行。最好的解决方法是使抽象类构造函数处理name属性:

abstract class Abstract {

  constructor (protected name: string) {
    this.abstractMethod();
  }

  protected abstract abstractMethod (): void;
}

class Concrete extends Abstract {
  constructor() {
    super("Concrete");
  }
  protected abstractMethod () {
    console.log(this, this.name); // Concrete, undefined
  }
}

new Concrete();