面试题答案
一键面试1. TypeScript装饰器在编译阶段的转换过程
TypeScript装饰器在编译阶段,会根据目标ES版本将装饰器相关代码转换为ES标准可执行的代码。通常,装饰器会被转换为函数调用的形式。当装饰器应用于类、方法、属性或参数时,TypeScript编译器会在运行时通过特定的函数调用来应用装饰器逻辑。例如,类装饰器会在类定义之后立即调用,将类构造函数作为参数传递给装饰器函数。
2. 类装饰器编译前后代码结构变化示例
编译前(TypeScript代码)
function classDecorator(target: Function) {
console.log('Class Decorator applied to', target.name);
return class extends target {
newProperty = 'New property added by decorator';
constructor(...args: any[]) {
super(...args);
console.log('Constructor of decorated class');
}
};
}
@classDecorator
class MyClass {
originalProperty = 'Original property';
constructor() {
console.log('Constructor of original class');
}
}
编译后(ES5代码,以Babel转换结果为例,假设target为ES5)
function classDecorator(target) {
console.log('Class Decorator applied to', target.name);
return function () {
function _class() {
console.log('Constructor of decorated class');
_class2.apply(this, arguments);
}
var _class2 = target;
_class.prototype = Object.create(_class2 && _class2.prototype);
_class.prototype.constructor = _class;
_class.prototype.newProperty = 'New property added by decorator';
return new _class();
};
}
var MyClass = (function () {
function MyClass() {
console.log('Constructor of original class');
}
MyClass.prototype.originalProperty = 'Original property';
return MyClass;
}());
MyClass = classDecorator(MyClass);
在编译前,使用@classDecorator
语法糖将装饰器应用到MyClass
类。编译后,装饰器函数classDecorator
以函数调用的形式作用于MyClass
类的构造函数,同时对类的结构进行了修改,添加了新属性并修改了构造函数逻辑。