下面是mycode:
1)DecorTest.ts:
export const symbolPrefix = Symbol('prefix');
export const controller = (path) => (target) =>
target.prototype[symbolPrefix] = path;
2)TestDecor.ts
import {controller} from './DecorTest';
@controller('aaa')
export class TestDeco {
private name: string;
constructor(AName: string) {
this.name = AName;
}
}
3)app.ts
import {TestDeco } from './router/TestDecor';
const testdec = new TestDeco('bb');
var keys = [];
for(var i in testdec) {
if(testdec.hasOwnProperty(i)) {
keys.push(i)
}
}
4)然后,我编译它,编译器显示错误:TestDecor_1.TestDeco不是app.js中的构造函数
下面的5)是app.js编译的
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const Koa = require('koa');
const app = new Koa();
const KoaRouter = require('koa-router');
const mainrouter_1 = require("./router/mainrouter");
const TestDecor_1 = require("./router/TestDecor");
const testdec = new TestDecor_1.TestDeco('bb'); //error locate this line
var keys = [];
for (var i in testdec) {
if (testdec.hasOwnProperty(i)) {
keys.push(i);
}
}
console.log(keys);
答案 0 :(得分:1)
If we look at the documentation for decorators:
如果类装饰器返回一个值,它将用提供的构造函数替换类声明。
现在让我们来看看装饰者:
export const controller = (path) => (target) => target.prototype[symbolPrefix] = path;
在编写箭头函数时,不使用大括号会创建隐式返回,并且赋值表达式返回正在分配的值,因此装饰器的最终结果将返回path
所有的内容。
以下是使用情况:
// this...
@controller('aaa')
export class TestDeco {
private name: string;
constructor(AName: string) {
this.name = AName;
}
}
// roughly becomes this
export const TestDeco = 'aaa'
然后,new TestDeco()
是有问题的,因为将new
与字符串一起使用没有意义,并且JS生气了。
因此,解决方案是在装饰器的代码周围放置一组括号,以确保它在不实际返回任何内容的情况下更改原型。
export const controller = (path) => (target) => {
target.prototype[symbolPrefix] = path;
}