我刚开始使用Angular版本2,偶然发现了@Component Decorator。我记得AngularJS(1.x)也有装饰器的概念,它用于扩展/更改任何服务的默认实现。
看起来就像在Angular 2中,他们没有改变/扩展默认功能,而是向从类(使用@Component)到属性(使用Input()/Output()装饰符)的内容添加元数据,管道和服务等列表不胜枚举。
有人能提供两者在概念/实际工作方面的区别吗?
谢谢。深度
发布于 2017-09-06 17:57:03
AngularJS
AngularJS装饰器是一个OOP pattern。
在AngularJS中很少使用它来扩展内置对象的行为。例如,下面的implementation使用$provider.decorator()截取$log.debug()调用并动态地预置时间戳信息。
$provide.decorator('$log', [
"$delegate", function ($delegate) {
// Save the original $log.debug()
var debugFn = $delegate.debug;
$delegate.debug = function () {
var args = [].slice.call(arguments),
now = DateTime.formattedNow();
// Prepend timestamp
args[0] = supplant("{0} - {1}", [now, args[0]]);
// Call the original with the output prepended with formatted timestamp
debugFn.apply(null, args)
};
return $delegate;
}
]);角度
Angular装饰器是a language-feature:
提供了方便的声明性语法来修改类声明的形状。此功能可用于多种目的,包括修改已声明成员的描述符(@nonconfigurable/@enumerable)、添加元数据(如Angular所使用的)等等。它允许附加访问
Angular使用它将元数据附加到类、类成员(属性)和方法参数。要了解Angular是如何做到这一点的,请阅读Implementing custom component decorator in Angular。
在大于4的版本中,Angular将不再在运行时动态评估装饰器,而是将使用静态代码分析来提取装饰器描述符中指定的元数据。
https://stackoverflow.com/questions/46067921
复制相似问题