[英]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.