简体   繁体   English

如何在JetBrains IDE中为闭包指定“this”值的类型?

[英]How can I specify the type of the “this” value for a closure in JetBrains IDEs?

JetBrains has an old blog post about JSDoc annotations that explains how to inform the IDE of variable types http://blog.jetbrains.com/webide/2012/10/validating-javascript-code-with-jsdoc-types-annotations/ . JetBrains有一篇关于JSDoc注释的老博文,解释了如何通知IDE变量类型http://blog.jetbrains.com/webide/2012/10/validating-javascript-code-with-jsdoc-types-annotations/

I still, however, cannot seem to find a way to tell the IDE that the "this" value in many jQuery callbacks are HTMLElements. 但是,我仍然无法找到告诉IDE许多jQuery回调中的“this”值是HTMLElements的方法。 For example: 例如:

/**
 * Enable input
 * @returns {SomeConstructor}
 */
SomeConstructor.prototype.enableInput = function(){
    this.$markup.find('input').each(function(){
        this.disabled = false;
    });
    return this;
};

The above example will still produce a warning in the IDE - "Potentially invalid usage of this". 以上示例仍将在IDE中生成警告 - “可能无效使用此”。

在此输入图像描述 How can I specify that "this" refers to a HTMLElement object? 如何指定“this”引用HTMLElement对象?

EDIT: 编辑:

After looking through the JSDoc documentation I found the @this annotation http://usejsdoc.org/tags-this.html . 在查看JSDoc文档后,我找到了@this注释http://usejsdoc.org/tags-this.html @this will allow you to specify a "this" value for an entire function, but in the posted example the IDE will think it's returning an HTMLElement rather than a SomeConstructor. @this将允许您为整个函数指定“this”值,但在发布的示例中,IDE将认为它返回的是HTMLElement而不是SomeConstructor。

@de1mar in the comments nailed it. @ de1mar在评论中钉了它。 The trick is to place /**@this {HTMLElement} just before the closure. 诀窍是在关闭之前放置/ ** @ this {HTMLElement}。 So, for example: 所以,例如:

/**
 * Enable input
 * @returns {SomeConstructor}
 */
SomeConstructor.prototype.enableInput = function(){
    this.$markup.find('input').each(/**@this {HTMLElement}*/function(){
        this.disabled = false;
    });
    return this;
};

Or, 要么,

SomeConstructor.prototype.listenForCheck = function(){
    this.$markup.find('input[type=checkbox]').on('click', /**@this {HTMLInputElement}*/ function(){
        //Do something
    });
};

Should be useful for anyone out there writing jQuery in a jetbrains IDE. 对于那些在jetbrains IDE中编写jQuery的人来说应该是有用的。 Thanks @del1mar! 谢谢@ del1mar!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM