简体   繁体   English

javascript - jshint可能严格违规错误

[英]javascript - jshint possible strict violation error

I am developing a plugin of table export at client-side. 我正在客户端开发一个表导出插件。 Plugin works fine. 插件工作正常。 But when I validated my code in jshint, it throws me an error saying possible strict violation. 但是当我在jshint中验证我的代码时,它会抛出一个错误,指出可能存在严格的违规行为。 Below is the function: 以下是功能:

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!');
        }
    }

And it says: "If a strict mode function is executed using function invocation, its 'this' value will be undefined." 它说:“如果使用函数调用执行严格模式函数,它的'this'值将是未定义的。”

Complete code of plugin is available on https://jsfiddle.net/t47L8yyr/ 完整的插件代码可在https://jsfiddle.net/t47L8yyr/上找到

How do I resolve this ? 我该如何解决这个问题? any other solution than using /*jshint validthis:true*/ 任何其他解决方案,而不是使用/*jshint validthis:true*/

Inside your disableExport() function, you make references to this . disableExport()函数中,您可以引用this If you invoke the function normally... 如果您正常调用该功能......

disableExport()

... in strict Javascript mode , this will be undefined. ...在strict Javascript模式下this将是未定义的。 Outside strict mode, this will usually be the window object. 在严格模式之外, this通常是window对象。 So: 所以:

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

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

This is not good. 这个不好。 If you want to target the window object, use it explicitly: 如果要定位window对象,请明确使用它:

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

If you're attempting to use this as a parameter to the function, invoking it with Function.call() or Function.apply() , it's much better to take an actual parameter than to use this : 如果你试图使用this作为参数传递给函数,与调用它Function.call()Function.apply()这是更好的采取一个实际的参数,而不是使用this

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

You can then call disableExport(window) or any other target . 然后,您可以调用disableExport(window)或任何其他target It's usually better to use this only when dealing with methods of an object, defined in the prototype of a function, or through the ES6 class syntax . 它通常是更好地使用this与对象的方法,在规定的交易时只有prototype ,或者通过一个函数的ES6 class语法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM