Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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."

Complete code of plugin is available on https://jsfiddle.net/t47L8yyr/

How do I resolve this ? any other solution than using /*jshint validthis:true*/

like image 969
Valay Avatar asked Jun 01 '17 14:06

Valay


1 Answers

Inside your disableExport() function, you make references to this. If you invoke the function normally...

disableExport()

... in strict Javascript mode, this will be undefined. Outside strict mode, this will usually be the window object. 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).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:

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

You can then call disableExport(window) or any other 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.

like image 86
slezica Avatar answered Nov 13 '22 20:11

slezica