为什么JSHINT抱怨这是严格的违规行为? [英] Why is JSHINT complaining that this is a strict violation?

查看:146
本文介绍了为什么JSHINT抱怨这是严格的违规行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我认为这可能与使用此关键字进行严格违规并显示模块模式

我有以下代码:

function gotoPage(s){
    if(s<=this.d&&s>0){this.g=s; this.page((s-1)*this.p.size);}
}

function pageChange(event, sorter) {
    var dd = event.currentTarget;
    gotoPage.call(sorter, dd[dd.selectedIndex].value);
}

JSHINT(JSLINT)抱怨。它说严格违规。突出显示的行:

And JSHINT (JSLINT) is complaining. It says "Strict violation." for the highlighted line:

我是否使用 Function.call()然后引用该实例,不知何故不合适?

Is my use of Function.call() and then referencing the instance, somehow inappropriate?

这被认为是不好的风格吗?

Is this considered to be bad style?

推荐答案

JSHint说可能严格违规,因为你在这个里面的东西,据我所知,它不是一种方法。

JSHint says "Possible strict violation" because you are using this inside something that, as far as it can tell, is not a method.

在非严格模式下,调用 gotoPage(5)会将绑定到全局对象(<浏览器中的code>窗口。在严格模式下,这个将是 undefined ,你会遇到麻烦。

In non-strict mode, calling gotoPage(5) would bind this to the global object (window in the browser). In strict mode, this would be undefined, and you would get in trouble.

据推测,你的意思是用一个绑定的这个上下文调用这个函数,例如 gotoPage.bind(myObj)(5) gotoPage.call(myObj,5)。如果是这样,您可以忽略JSHint,因为您不会生成任何错误。但是,它告诉你你的代码对于阅读它的人来说都不清楚,因为使用这个里面的东西显然不是一种方法,这是非常令人困惑的。简单地将对象作为参数传递会更好:

Presumably, you mean to call this function with a bound this context, e.g. gotoPage.bind(myObj)(5) or gotoPage.call(myObj, 5). If so, you can ignore JSHint, as you will not generate any errors. But, it is telling you that your code is unclear to anyone reading it, because using this inside of something that is not obviously a method is quite confusing. It would be better to simply pass the object as a parameter:

function gotoPage(sorter, s) {
    if (s <= sorter.d && s > 0) {
        sorter.g = s;

        sorter.page((s - 1) * sorter.p.size);
    }
}

function pageChange(event, sorter) {
    var dd = event.currentTarget;
    gotoPage(sorter, dd[dd.selectedIndex].value);
}

这篇关于为什么JSHINT抱怨这是严格的违规行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆