我正在客户端开发一个表导出插件.插件工作正常.但是当我在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!');
}
}
Run Code Online (Sandbox Code Playgroud)
它说:"如果使用函数调用执行严格模式函数,它的'this'值将是未定义的."
完整的插件代码可在https://jsfiddle.net/t47L8yyr/上找到
我该如何解决这个问题?除了使用之外的任何其他解/*jshint validthis:true*/
在您的disableExport()函数内部,您可以参考this.如果您正常调用该功能......
disableExport()
Run Code Online (Sandbox Code Playgroud)
...在strictJavascript模式下,this将是未定义的.外部严格模式,this通常是window对象.所以:
disableExport() // `this` will be `window`
"use strict"
disableExport() // `this` will be undefined
Run Code Online (Sandbox Code Playgroud)
这个不好.如果要定位window对象,请明确使用它:
_(window).exportPlugin(...) // reference `window`, not `this`
Run Code Online (Sandbox Code Playgroud)
如果你试图this用作函数的参数,用Function.call()or 调用它Function.apply(),那么采用一个实际的参数比使用它更好this:
function disableExport(target) {
if(_(target).exportPlugin !== undefined) {
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以打电话disableExport(window)或任何其他target.通常最好this只在处理对象的方法时使用,在prototype函数中定义,或者通过ES6 class语法.
| 归档时间: |
|
| 查看次数: |
119 次 |
| 最近记录: |