首先我们先创建一个Name类
class Name {
constructor() {
}
consoleMsg() {
console.log(22222)
}
}
然后我们再Greeter类中调用Name类的consoleMsg方法,在不使用继承的情况下我们可能会这么写
class Greeter {
property = "property";
hello: string;
newProperty: Name
constructor(hello: string) {
this.hello = hello
this.newProperty = new Name()
}
getMsg() {
this.newProperty.consoleMsg()
}
}
自从有了装饰器后,我们可以使用装饰器来美化我们的代码
type Ctor<T> = new (...args: any[]) => T
function auto<T>(className: Ctor<T>) {
return function (target: any, attr: any) {
// target 是类的原型对象, attr 属性的名称 (url)
console.log(target);
console.log(attr);
console.log(className)
target[attr] = new className();
}
}
class Greeter {
property = "property";
hello: string;
@auto(Name)
newProperty: Name
constructor(hello: string) {
this.hello = hello
}
getMsg() {
this.newProperty.consoleMsg()
}
}
new Greeter('你好').getMsg();
另外我们可以把auto方法单独封装出去,这样我们的代码是不是更简洁来那!
下面我们执行下代码,看下结果: