繁体   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