JavaScript 注释 [英] JavaScript annotations

查看:24
本文介绍了JavaScript 注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有 JavaScript 注释?

当然 JavaScript 没有它们,但是否有额外的库或建议的语言扩展,例如

Of course JavaScript doesn't have them, but are there additional libraries or proposed language extension, for example

@type {folder.otherjsmodule.foo}
function(){
    foo = folder.otherjsmodule.foo();
    ...
    return foo;
};

推荐答案

更新:现在有一个建议 在 JavaScript 中使用适当的装饰器.它目前是第一阶段,你可以在 BabelJS 和 traceur 中使用它.

Update: There now exists a proposal for proper decorators in JavaScript. It's currently stage 1 and you can use it in BabelJS and traceur.

几个库,就像前面提到的闭包在注释中使用注释一样,闭包编译器甚至断言类型它可以在编译时.然而,这些并不是经典意义上的实际注释".

Several libraries, like the mentioned before closure use annotations in comments, the closure compiler even asserts types as much as it can in compile time. However, these are not actual 'annotations' in the classical sense.

与显而易见"的答案不同 - 是的,有 JavaScript 注释,一些运行时支持它们.

Unlike the 'obvious' answer - Yes, there are JavaScript annotations, some run-times support them.

例如

(function(){
    "use strict";
    //code in strict mode
})();

这将导致函数内部执行严格模式.最近在 Mozilla 中,我们得到了:

This will cause strict mode execution inside the function. More recently in Mozilla we've gotten:

(function(){
    "use asm";
    //code in asmjs
})();

这将导致代码在 asmjs 模式下运行,优化转译.

Which will cause the code to run in asmjs mode, optimizing for transpiling.

是的,虽然面向方面的编程和注释在 JS 中广泛不常见,但完全有可能编写一个接受函数的库,查看它的 .toString,找出这样的注释在哪里结束和执行相关代码,然后是函数的其余部分.

Yes, while aspect oriented programming and annotations are widely uncommon in JS, it's perfectly possible to write a library that accepts a function, looks at its .toString, figures out where such annotations end and executes the relevant code and then the rest of the function.

例如

an(function(){
    "validate user"; // this could be something you implement yourself
    "use strict";
})();

创建一个执行此操作的库非常简单,它需要一些讨厌的代码(使用 Function 构造函数并将函数解析为字符串),但这当然是可能的.它甚至可以在新的开发工具中调试,而且速度几乎与原生函数一样快.

Creating a library that does this is pretty simple, it would require some nasty code (using a Function constructor and parsing the function as a string) but it's certainly possible. It's even debuggable in the new dev-tools and it's almost as fast as a native 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
});

这篇关于JavaScript 注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆