2017-06-01 37 views
6

我正在开发客户端的表导出插件。插件工作正常。但是当我使用jshint验证我的代码时,它会引发错误,说明可能存在严重的违规行为。下面是函数:javascript - 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!'); 
     } 
    } 

它说:“如果使用函数调用执行的严格模式功能,其‘本’值将是未定义”插件

完整的代码可以在https://jsfiddle.net/t47L8yyr/

我该如何解决这个问题?除了使用任何其他解决方案/*jshint validthis:true*/

+0

伙计们,当OP明确表示在另一个问题中接受的答案对他无用时,我们将问题解决为重复。让我们重新打开它 – slezica

+0

@slezica谢谢 – Valay

+0

给它一段时间。当它被重新打开时,我会留下一个答案 – slezica

回答

5

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

disableExport() 

...在strict Javascript modethis将是不确定的。在严格模式之外,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。仅当处理对象的方法,定义为 中的函数的prototype或通过ES6 class syntax时,通常 才更好地使用this

+0

感谢您的回答。你可以在https://jsfiddle.net/t47L8yyr/上给我看看。我在创建后将插件分配给'_(this).exportPlugin'。 – Valay