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