在构造函数中或在打字稿外部定义定位器有什么优缺点?

What pros and cons in defining the locators in the constructor or outside in typescript?

我将从 java 开始使用量角器(打字稿)测试自动化。正如我所见,打字稿世界中的很多人都喜欢在构造函数中定义定位器,例如:

export default class SignInPage extends BasePage {
  private readonly _usernameInputLocator: By;
  private readonly _passwordInputLocator: By;

  constructor() {
    super();
    this._usernameInputLocator = by.name('username');
    this._passwordInputLocator = by.name('password');
  }

}

而不是我的普遍看法,例如:

export default class SignInPage extends BasePage {

  private readonly _usernameInputLocator: By = by.name('username');
  private readonly _passwordInputLocator: By = by.name('password');

}

你能不能告诉我这两种方法有什么区别。

没有太大区别。第一个版本允许您在初始化程序中使用构造函数参数或引用其他属性;第二个更短更整洁,但在内部,代码只是被提升到构造函数中,所以没有区别。

生成的 javascript 在任何一种情况下都是相同的,除了第二个具有自动生成的构造函数的方法在调用它之前测试是否存在超级构造函数。