【发布时间】:2018-04-02 23:48:13
【问题描述】:
我正在学习 Angular 2+ 中使用的 Typescript 中的装饰器。我知道装饰器只是函数。
我发现有时装饰器必须返回一个函数,而有时逻辑在装饰器函数内部执行而没有任何返回。
考虑类装饰器
@course
class Person {
constructor() {
console.log("Test")
}
}
装饰课程定义如下。它定义了 Person.prototype 的一些属性。它什么也不返回。
function course(target) {
Object.defineProperty(target.prototype, 'course', {value: () => "Angular 2"})
}
鉴于:
@course{
course:"Sample_decorator"
}
class Person {
constructor() {
console.log("Test")
}
}
装饰课程定义如下。它返回一个函数。
function course(config) {
return function (target) {
Object.defineProperty(
target.prototype,
'course',
{value: () => config.course,
writable: true,
enumerable: true,
configurable: true
} // 2
)
}
}
我无法理解返回函数是如何自动调用的。因为它涉及两次调用。
如果我手动调用上述函数:
说
test = {
course:"Sample_decorator_testing"
}
首先调用装饰器函数:
var decor = course(test)
它返回一个必须再次调用才能运行defineproperty的函数。所以
decor(Person)
那么只有
sample = new Person
sample.course() \\ outputs "Sample_decorator_testing"
那么它怎么会自动调用返回函数呢。
【问题讨论】:
-
装饰器由于在 Angular 2+ 中的使用而变得流行。在 Angular 中,通过 TypeScript 可以使用装饰器,但在 JavaScript 中,它们目前是第 2 阶段的提案,这意味着它们应该成为该语言未来更新的一部分。 sitepoint.com/javascript-decorators-what-they-are
-
Angular 4 中使用的打字稿
标签: javascript angular typescript decorator