簡體   English   中英

javascript - jshint可能嚴格違規錯誤

[英]javascript - jshint possible strict violation error

我正在客戶端開發一個表導出插件。 插件工作正常。 但是當我在jshint中驗證我的代碼時,它會拋出一個錯誤,指出可能存在嚴格的違規行為。 以下是功能:

function disableExport(){
        if(_(this).exportPlugin !== undefined){
            _(this).exportPlugin.setStyle('pointer-events', 'none');
            _(this).exportPlugin.find('.ebIcon').removeModifier('interactive','ebIcon');
            _(this).exportPlugin.find('.ebIcon').setModifier('disabled','','ebIcon');
        }else{
            console.log('ERROR!');
        }
    }

它說:“如果使用函數調用執行嚴格模式函數,它的'this'值將是未定義的。”

完整的插件代碼可在https://jsfiddle.net/t47L8yyr/上找到

我該如何解決這個問題? 任何其他解決方案,而不是使用/*jshint validthis:true*/

disableExport()函數中,您可以引用this 如果您正常調用該功能......

disableExport()

...在strict Javascript模式下this將是未定義的。 在嚴格模式之外, this通常是window對象。 所以:

disableExport() // `this` will be `window`

"use strict"
disableExport() // `this` will be undefined

這個不好。 如果要定位window對象,請明確使用它:

_(window).exportPlugin(...) // reference `window`, not `this`

如果你試圖使用this作為參數傳遞給函數,與調用它Function.call()Function.apply()這是更好的采取一個實際的參數,而不是使用this

function disableExport(target) {
  if(_(target).exportPlugin !== undefined) {
    // ...
  }
}

然后,您可以調用disableExport(window)或任何其他target 它通常是更好地使用this與對象的方法,在規定的交易時只有prototype ,或者通過一個函數的ES6 class語法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM