2013-08-30 22 views
2

我試圖重新定義舊版IE的Array.prototype.indexOf。根據Google Closure Compiler,我無法正確輸入。鍵入indexOf使用Closure編譯器重新定義

它說@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 {Object}@this {Array}(儘管它沒有多大意義)返回此更加晦澀消息:

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) { 
^ 

任何暗示如何正確地做到這一點?

回答

3

您可以使用@suppress {duplicate}無視這樣的警告:

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

我不知道的含義重新定義的方法對在高級模式從封閉編譯器優化,雖然。

+0

謝謝,就是我在找的東西! –

+0

重新定義應該沒問題,只要簽名與原件完全匹配,並且該功能不會導致副作用(因爲原件沒有)。這就是其他警告的原因。 –

2

數組方法是通用的,它們實際上應該採用類似數組的值。最新的關閉編譯器將其定義爲:

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

考慮升級到最新的編譯器的版本。

+0

謝謝,但只是賦值,返回相同的警告'source.js:488:WARNING - 變量Array.prototype.indexOf用類型function(this:Array,*,number =)重新定義:數字,原始定義在externs.zip/ /es3.js:633與類型函數(this:Object,*,number =):number'。我正在使用幾周前下載的版本2508M。我相信這是最新的。我得到警告的原因可能是因爲我使用'「reportUnknownTypes = CheckLevel.WARNING」'進行編譯,以便進行嚴格的輸入。 –

+0

報告未知類型不會影響這一點。你編譯器發佈的可能性很大。 – John

+0

這很奇怪,我的構建來自一週前運行'svn checkout http://closure-compiler.googlecode.com/svn/trunk/closed-compiler'。版本是2508M。 –