【问题标题】:javascript - jshint possible strict violation errorjavascript - jshint 可能的严格违反错误
【发布时间】:2017-11-02 17:50:56
【问题描述】:

我正在客户端开发一个表格导出插件。插件工作正常。但是当我在 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*/

之外的任何其他解决方案

【问题讨论】:

  • 伙计们,当 OP 明确表示另一个问题中接受的答案对他没有用时,我们将问题关闭为重复。让我们重新打开它
  • @slezica 谢谢
  • 等一下。当它重新打开时,我会留下答案
  • @slezica — 他们在该附带条件中进行了编辑(没有解释为什么它不可接受)关闭之后。
  • “除了使用 /*jshint validthis:true*/ 之外的任何其他解决方案”——这有什么问题?

标签: javascript jshint


【解决方案1】:

在您的 disableExport() 函数中,您引用了 this。如果你正常调用函数...

disableExport()

...在strict Javascript mode 中,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 syntax

【讨论】:

  • 感谢您的回答。你能在jsfiddle.net/t47L8yyr 给我看这个吗?创建插件后,我将其分配给_(this).exportPlugin
猜你喜欢
  • 2015-12-05
  • 2012-08-16
  • 2015-05-19
  • 2016-06-18
  • 2013-05-09
  • 2013-08-10
  • 2012-07-24
  • 2015-05-30
相关资源
最近更新 更多