2

Array.prototype.indexOf古い IE バージョン用に再定義しようとしています。Google Closure Compiler によると正しく入力できません。

の型@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) {
^

驚くべきことに、by を変更@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) {
^

適切に行う方法に関するヒントはありますか?

4

2 に答える 2

3

@suppress {duplicate}この警告を無視するために使用できます。

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

ただし、ADVANCED モードでの Closure Compiler からの最適化で、メソッドを再定義することの意味についてはよくわかりません。

于 2013-08-30T14:06:57.720 に答える
2

配列メソッドは一般的であり、実際には配列のような値を取る必要があります。最新の Closure Compiler では、次のように定義されています。

/**
 * 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) {
     // ...
  }
}

Compiler の最新リリースへのアップグレードを検討してください。

于 2013-09-03T17:26:16.410 に答える