有什么办法可以hook到TypeScript中类的声明过程吗?
例如考虑以下类(class)
class Foo extends Bar
{
constructor() { super(); }
}
我目前通过像这样手动调用编织器来将方面应用到这种类型:
weaver.applyAspects(Foo);
意思是我修改了类中某些方法的行为。 我宁愿看到这只是通过在上述情况下继承“Bar”父类(super class)而自动发生。
在构造函数中做一些时髦的事情似乎是错误的,因为这将应用于每个新实例,而不仅仅是原型(prototype)本身。
我想我可以覆盖 __extends 函数(在生成的 javascript 输出中使用),但这似乎也有点古怪。
还有其他选择吗?
最佳答案
如果您想在 TypeScript 中使用 AOP,您可以通过为其提供定义来使用现有的 AOP 框架。这是一个使用 jQuery.aop 的完整示例。
以这种方式使用 AOP 不会影响您现有的任何定义,因为 AOP 代码在您正在横切的代码中是不可见的。
aop.d.ts
declare class Advice {
unweave(): void;
}
declare interface PointCut {
target: Object;
method: string;
}
declare class Aop {
before: (pointCut: PointCut, advice: Function) => Advice[];
after: (pointCut: PointCut, advice: Function) => Advice[];
afterThrow: (pointCut: PointCut, advice: Function) => Advice[];
afterFinally: (pointCut: PointCut, advice: Function) => Advice[];
around: (pointCut: PointCut, advice: Function) => Advice[];
introduction: (pointCut: PointCut, advice: Function) => Advice[];
}
interface JQueryStatic {
aop: Aop;
}
app.ts
/// <reference path="jquery.d.ts" />
/// <reference path="aop.d.ts" />
class ExampleClass {
exampleMethod() {
alert('Hello');
}
}
jQuery.aop.before(
{ target: ExampleClass, method: 'exampleMethod' },
function () { alert('Before exampleMethod'); }
);
jQuery.aop.after(
{ target: ExampleClass, method: 'exampleMethod' },
function () { alert('After exampleMethod'); }
);
var example = new ExampleClass();
example.exampleMethod();
示例来源:AOP with TypeScript .
更新
要对一个类和所有兼容类添加相同的关注点,不能重复使用基类点。这是因为wrapper是原始基类函数包裹在点中,对于扩展基类的类来说会是错误的实现。
唯一有效的情况是你的函数只调用了 super()
,在这种情况下它仍然可以工作。
以下是我如何将相同的关注点添加到许多类中 - AopHelper 只需要在您的程序中存在一次:
/// <reference path="jquery.d.ts" />
/// <reference path="aop.d.ts" />
class ExampleClass {
exampleMethod() {
alert('Hello');
}
}
class SecondClass extends ExampleClass {
exampleMethod() {
alert('World');
}
}
class AopHelper {
static weave(targets: Object[], method: string, point: Function, advice: Function) {
for (var i = 0; i < targets.length; i++) {
point({ target: targets[i], method: method }, advice );
}
}
}
var classes: any[] = [ExampleClass, SecondClass];
AopHelper.weave(classes, 'exampleMethod', jQuery.aop.before, () => { alert('Before exampleMethod'); });
AopHelper.weave(classes, 'exampleMethod', jQuery.aop.after, () => { alert('After exampleMethod'); });
var example = new SecondClass();
example.exampleMethod();
关于javascript - TypeScript 将方面应用到类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13179210/