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*/
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With