Update: 现在有一个proposal https://github.com/wycats/javascript-decoratorsJavaScript 中正确的装饰器。目前是stage 1 https://github.com/tc39/ecma262你可以在 BabelJS 和 Traceur 中使用它。
一些库,比如之前提到的闭包,在注释中使用注释,闭包编译器 https://developers.google.com/closure/compiler/甚至在编译时尽可能多地断言类型。然而,这些并不是经典意义上的实际“注释”。
与“显而易见”的答案不同 - 是的,有 JavaScript 注释,一些运行时支持它们。
例如
(function(){
"use strict";
//code in strict mode
})();
这将导致函数内部严格模式执行。最近在 Mozilla 中我们得到了:
(function(){
"use asm";
//code in asmjs
})();
这将导致代码在 asmjs 模式下运行,优化转译。
我可以在我的库中使用这些类型的注释吗?
是的,虽然面向方面的编程和注释在 JS 中并不常见,但完全有可能编写一个接受函数的库,查看它的函数.toString
,找出此类注释的结束位置并执行相关代码,然后执行函数的其余部分。
例如
an(function(){
"validate user"; // this could be something you implement yourself
"use strict";
})();
创建一个执行此操作的库非常简单,它需要一些讨厌的代码(使用 Function 构造函数并将函数解析为字符串),但这当然是可能的。它甚至可以在新的开发工具中进行调试,并且几乎与本机函数一样快。
建议的语法可以是:
an.add("assertEmail",function(x){
if(!emailRegex.test(x){
throw new Error("Invalid call to function - expected email got",x);
}
});
// later on
an(function subscribeToNewsLetter(x){
"assertEmail";
var xhr = new XMLHttpRequest();
//send email
});