【问题标题】:How can I specify the type of the "this" value for a closure in JetBrains IDEs?如何在 JetBrains IDE 中为闭包指定“this”值的类型?
【发布时间】:2016-05-09 10:51:22
【问题描述】:

JetBrains 有一篇关于 JSDoc 注释的旧博客文章解释了如何通知 IDE 变量类型 http://blog.jetbrains.com/webide/2012/10/validating-javascript-code-with-jsdoc-types-annotations/

然而,我似乎仍然无法找到一种方法来告诉 IDE 许多 jQuery 回调中的“this”值是 HTMLElements。例如:

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

上面的例子仍然会在 IDE 中产生一个警告——“可能无效地使用 this”。

如何指定“this”指的是 HTMLElement 对象?

编辑:

在浏览了 JSDoc 文档后,我发现了 @this 注释 http://usejsdoc.org/tags-this.html。 @this 将允许您为整个函数指定“this”值,但在发布的示例中,IDE 会认为它返回的是 HTMLElement 而不是 SomeConstructor。

【问题讨论】:

  • 那么你用的是phpstorm还是webstorm?
  • 这并不能回答你的问题,但是...... jQuery 的每个函数的回调签名实际上是Function( Integer index, Element element ),其中element === this,所以你可以声明参数并注释第二个的类型?
  • 使用 PHPStorm,但问题适用于两者。是的,这是@BenGriffiths 的一种方法,但它也适用于 $(element).on('click', function(){ //some code}) 之类的东西:/.
  • 在 WebStorm/PhpStorm 2016.2 中不会针对这种情况突出显示“可能无效使用 this”。目前,我可能只建议像这样注释内部函数表达式this.$markup.find('input').each(/** @this {HTMLElement} */ function(){});
  • @de1mar 您应该将此作为答案发布 - 它有效!我曾多次尝试过同样的方法,但将我的 cmets 放在函数中(/**@this {HTMLElement}*/),所以它不起作用。看着所有的波浪线消失,我真的很放心:)。

标签: javascript jquery callback phpstorm webstorm


【解决方案1】:

cmets 中的@de1mar 成功了。诀窍是在闭包之前放置 /**@this {HTMLElement}。所以,例如:

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

或者,

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

应该对任何在 jetbrains IDE 中编写 jQuery 的人有用。谢谢@del1mar!

【讨论】:

    猜你喜欢
    • 2019-11-13
    • 1970-01-01
    • 2020-08-30
    • 1970-01-01
    • 2014-03-31
    • 2023-03-18
    • 2013-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多