{
"compilerOptions": {
"experimentalDecorators": true
}
}
function sealed(constructor: Function) {
Object.seal(constructor);
Object.seal(constructor.prototype);
}
@sealed
class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
}
function color(value: string) {
return function(target: Function) {
target.prototype.color = value;
};
}
@color('red')
class Car {}
function log(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function(...args: any[]) {
console.log(`调用 ${propertyKey},参数:`, args);
const result = originalMethod.apply(this, args);
console.log(`返回:`, result);
return result;
};
return descriptor;
}
class Calculator {
@log
add(a: number, b: number): number {
return a + b;
}
}
function configurable(value: boolean) {
return function(
target: any,
propertyKey: string,
descriptor: PropertyDescriptor
) {
descriptor.configurable = value;
};
}
class Point {
private _x: number;
@configurable(false)
get x() {
return this._x;
}
}
function format(formatString: string) {
return function(target: any, propertyKey: string) {
let value: string;
const getter = function() {
return value;
};
const setter = function(newVal: string) {
value = formatString.replace('%s', newVal);
};
Object.defineProperty(target, propertyKey, {
get: getter,
set: setter
});
};
}
class Greeter {
@format('Hello, %s')
greeting: string;
}
function required(target: any, propertyKey: string, parameterIndex: number) {
console.log(`参数 ${parameterIndex} 在 ${propertyKey} 中是必需的`);
}
class Greeter {
greet(@required name: string) {
return `Hello, ${name}`;
}
}
function first() {
console.log('first(): factory');
return function(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
console.log('first(): called');
};
}
function second() {
console.log('second(): factory');
return function(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
console.log('second(): called');
};
}
class Example {
@first()
@second()
method() {}
}
function autobind(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
return {
configurable: true,
get() {
return originalMethod.bind(this);
}
};
}
class Printer {
message = 'Hello';
@autobind
print() {
console.log(this.message);
}
}
const printer = new Printer();
const print = printer.print;
print();
function measure(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function(...args: any[]) {
const start = performance.now();
const result = originalMethod.apply(this, args);
const end = performance.now();
console.log(`${propertyKey} 执行时间: ${end - start}ms`);
return result;
};
return descriptor;
}
class Service {
@measure
fetchData() {
}
}