Javascript 使用decorator中的prototype/Access基类属性访问派生类中的基类属性
我正在使用typescript,我正在为我的angular类编写一个自定义装饰程序。我想访问子类装饰器中的基类方法。或者使用子类原型访问基类方法。有没有办法做到这一点?问题将在下面详细解释 场景 我有一个基类,就像Javascript 使用decorator中的prototype/Access基类属性访问派生类中的基类属性,javascript,angular,typescript,Javascript,Angular,Typescript,我正在使用typescript,我正在为我的angular类编写一个自定义装饰程序。我想访问子类装饰器中的基类方法。或者使用子类原型访问基类方法。有没有办法做到这一点?问题将在下面详细解释 场景 我有一个基类,就像 export class Base { public init() { console.log('My base class function'); } } 我有一个派生类,它扩展了这个基类 export class Child extends Ba
export class Base {
public init() {
console.log('My base class function');
}
}
我有一个派生类,它扩展了这个基类
export class Child extends Base {
}
我想做的事
我正试图为派生类编写一个类似
@TestDecorator(['init'])
export class Child extends Base {
}
将从基类调用init方法
问题出在哪里
为了实现上述场景,我编写了如下代码
export function Tool<T extends Base>(methods: any[]) {
return function (target: Function) {
methods.forEach((item) => {
if (item === 'init') {
target.super.init() // Stuck here
}
})
}
}
请帮我解决这个问题。我被卡住了。谢谢我相信您正在寻找这样的产品:
export function Tool<T extends Base>(methods: any[]) {
return function (target: Function) {
return class extends target {
constructor(...args: any[]) {
super(...args)
methods.forEach((item) => {
if (item === 'init') {
super.init( );
}
})
}
}
}
}
导出函数工具(方法:任意[]){
返回函数(目标:函数){
返回类扩展了目标{
构造函数(…参数:任意[]){
超级(…args)
方法.forEach((项目)=>{
如果(项=='init'){
super.init();
}
})
}
}
}
}
要在回答时展开,因为decorator函数返回的是它所修饰的类的构造函数的替换项,所以它必须维护原始原型
在下面的示例中,由于TestDecorator
中缺少init()
方法而导致错误
类基{
公共init(){
log(“我的基类函数”);
}
}
函数TestDecorator(方法:任意[]){
返回函数(目标:任意){
返回类扩展了目标{
构造函数(…参数:任意[]){
超级(…args)
方法.forEach((项目)=>{
如果(项=='init'){
super.init();
}
})
}
}
}
}
@TestDecorator(['init'])//错误:类型“TestDecorator.(匿名类)”中缺少属性“init”,但类型“Child”中需要属性“init”。
类子扩展基{
}
设c=新的子对象();
校正装饰器
函数TestDecorator(方法:any[]{
返回函数(目标:任意){
返回类扩展了目标{
init(){}//定义init()
构造函数(…参数:任意[]){
超级(…args)
方法.forEach((项目)=>{
如果(项=='init'){
super.init();
}
})
}
}
}
}
如果类装饰器返回一个值,它将用提供的构造函数替换类声明
注意:如果您选择返回一个新的构造函数,您必须注意维护原始原型。运行时应用修饰符的逻辑不会为您这样做。
export function Tool<T extends Base>(methods: any[]) {
return function (target: Function) {
return class extends target {
constructor(...args: any[]) {
super(...args)
methods.forEach((item) => {
if (item === 'init') {
super.init( );
}
})
}
}
}
}
class Base {
public init() {
console.log('My base class function');
}
}
function TestDecorator<T extends Base>(methods: any[]) {
return function (target: any) {
return class extends target {
constructor(...args: any[]) {
super(...args)
methods.forEach((item) => {
if (item === 'init') {
super.init( );
}
})
}
}
}
}
@TestDecorator(['init']) // Error: Property 'init' is missing in type 'TestDecorator<Base>.(Anonymous class)' but required in type 'Child'.
class Child extends Base {
}
let c = new Child();
function TestDecorator<T extends Base>(methods: any[]) {
return function (target: any) {
return class extends target {
init() {} // Define init()
constructor(...args: any[]) {
super(...args)
methods.forEach((item) => {
if (item === 'init') {
super.init( );
}
})
}
}
}
}