[英]TypeScript Derived Class Properties in Base Constructor using String Literal in Get Method
One solution not discussed by this answer is to implement a get method in a derived class which returns a string literal (but not member property as this would essentially be the same issue):此答案未讨论的一种解决方案是在派生类中实现一个 get 方法,该方法返回字符串文字(但不是成员属性,因为这本质上是相同的问题):
class Base {
constructor() { console.log( this.color ) }
public get color(): string { return 'blue' }
}
class Literal extends Base {
public get color(): string { return 'red' }
}
class Member extends Base {
private _color: string = 'green'
public get color(): string { return this._color }
}
let b = new Base() // => 'blue'
let l = new Literal() // => 'red'
let m = new Member() // => undefined
Are there any issues/downfalls to using this approach, for example with efficiency, in the emitted JavaScript - as opposed to the solutions provided in the linked answer?与链接答案中提供的解决方案相比,在发出的 JavaScript 中使用这种方法是否存在任何问题/缺点,例如在效率方面?
A usual implication of class fields is that they provide overhead in child classes:类字段的一个常见含义是它们在子类中提供开销:
class Member extends Base {
protected _color: string = 'green'
public get color(): string { return this._color }
}
class Foo extends Member {
protected _color: string = 'orange'
}
_color
will be assigned to 'green' and then to 'orange' on Foo
instantiation. _color
将被分配给 'green',然后在Foo
实例化时分配给 'orange'。 Notice that _color
should be protected in order to be reassigned.请注意,
_color
应该受到保护才能重新分配。
This is not a big concern for string value but it exists and may be a problem if _color
is complex object that doesn't need to be instantiated for each instance.这不是字符串值的大问题,但它存在并且如果
_color
是不需要为每个实例实例化的复杂对象,则它可能是一个问题。
This can be solved by moving a property to class prototype:这可以通过将属性移动到类原型来解决:
interface Member extends Base {
_color: IComplexColor;
}
class Member extends Base {
public get color(): string { return this._color.toString() }
}
Member.prototype._color = new SomeComplexColorClass('green');
class Foo extends Member {}
Foo.prototype._color = new SomeComplexColorClass('orange');
Notice that in this case class declaration should be merged with interface, this results in _color
being public, because protected _color;
请注意,在这种情况下,类声明应与接口合并,这将导致
_color
为 public,因为protected _color;
without initializer would cause a problem with strictPropertyInitialization
compiler option.没有初始化程序会导致
strictPropertyInitialization
编译器选项出现问题。 This solution isn't idiomatic to TypeScript because it needs workarounds for typing system, but it results in cleaner output.此解决方案不是 TypeScript 惯用的,因为它需要针对键入系统的变通方法,但它会产生更清晰的输出。
This can be considered preliminary optimization for a class with string property and relatively short prototype chain.这可以认为是对具有字符串属性和相对较短原型链的类的初步优化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.