使用闭包编译器键入indexOf重新定义

Typing indexOf redefinition with Closure compiler

本文关键字:新定义 定义 indexOf 闭包 编译器      更新时间:2023-09-26

我正在尝试为旧IE版本重新定义Array.prototype.indexOf。根据谷歌闭包编译器,我在正确键入它时遇到了问题。

它说@this的类型是错误的。

if (!Array.prototype.indexOf) {
  /**                                                                                                                                                 
   * @this {Array}                                                                                                                                    
   * @param {*} item                                                                                                                                  
   * @param {number=} from: ignored 
   * @return {number}                                                                                                                                 
   */
  Array.prototype.indexOf = function(item, from) {
    // ...
  }
}

我得到以下输出

test.js:12: WARNING - variable Array.prototype.indexOf redefined with type '
function (this:Array, *, number=): number, original definition at '
externs.zip//es3.js:633 with type function (this:Object, *, number=): number
Array.prototype.indexOf = function(item, from) {
^

令人惊讶的是,将@this {Array}更改为@this {Object}(尽管这没有多大意义)会返回一条更模糊的消息:

test.js:12: WARNING - variable Array.prototype.indexOf redefined with type '
function (this:Object, *, number=): number, original definition at '
externs.zip//es3.js:633 with type function (this:Object, *, number=): number
Array.prototype.indexOf = function(item, from) {
^

有什么关于如何正确做的提示吗?

您可以使用@suppress {duplicate}忽略此警告:

/**
 * @this {Array}
 * @param {*} item
 * @param {number=} from: ignored
 * @return {number}
 * @suppress {duplicate}
 */
Array.prototype.indexOf = function(item, from) {
    // ...
}

不过,我不确定在ADVANCED模式下重新定义该方法对闭包编译器优化的影响。

数组方法是通用的,它们实际上应该采用类似于Array的值。最新的闭包编译器将其定义为:

/**
 * Available in ECMAScript 5, Mozilla 1.6+.
 * @param {T} obj
 * @param {number=} opt_fromIndex
 * @return {number}
 * @this {{length: number}|Array.<T>|string}
 * @nosideeffects
 * @template T
 * @see http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array/indexOf
 */
Array.prototype.indexOf = function(obj, opt_fromIndex) {};

简单地分配价值是可行的:

if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function(item, from) {
     // ...
  }
}

请考虑升级到最新版本的编译器。