为什么 JSHINT 抱怨这是一种严格的违规行为?
我认为这可能与严格违反使用重复this 关键字和揭示模块模式
我有这样的代码:
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) 正在抱怨。上面写着“严格违规”。对于突出显示的行:
我使用的是 Function.call()
和然后引用实例,不知何故不合适?
这被认为是不好的风格吗?
I think this may be a duplicate of Strict Violation using this keyword and revealing module pattern
I have this code:
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);
}
And JSHINT (JSLINT) is complaining. It says "Strict violation." for the highlighted line:
Is my use of Function.call()
and then referencing the instance, somehow inappropriate?
Is this considered to be bad style?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
JSHint 说“可能的严格违规”,因为您在某个东西中使用了
this
,据它所知,这不是一个方法。在非严格模式下,调用
gotoPage(5)
会将this
绑定到全局对象(浏览器中的window
)。在严格模式下,this
将会是未定义
,并且您会遇到麻烦。据推测,您的意思是使用绑定的
this
上下文调用此函数,例如gotoPage.bind(myObj)(5)
或gotoPage.call(myObj, 5)
。如果是这样,您可以忽略 JSHint,因为您不会生成任何错误。但是,它告诉您,您的代码对于任何阅读它的人来说都不清楚,因为在显然不是方法的内容中使用this
是相当令人困惑的。最好简单地将对象作为参数传递:JSHint says "Possible strict violation" because you are using
this
inside something that, as far as it can tell, is not a method.In non-strict mode, calling
gotoPage(5)
would bindthis
to the global object (window
in the browser). In strict mode,this
would beundefined
, and you would get in trouble.Presumably, you mean to call this function with a bound
this
context, e.g.gotoPage.bind(myObj)(5)
orgotoPage.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 usingthis
inside of something that is not obviously a method is quite confusing. It would be better to simply pass the object as a parameter:我收到一条关于不以大写字母开头的函数的消息。
I've had this message for a function that did not start with a capital letter.
如果您将函数声明为变量而不是使用标准函数声明,jshint 不会将其标记为严格违规。所以你可以执行以下操作 -
If you declare the function as a variable instead of using the standard function declaration, jshint will not flag this as a strict violation. So you may do the following -
如果您尝试实现一个方法,您可能需要分配给原型:
JSHint 在分配函数时不会发出警告。
If you're trying to implement a method, you might want to assign to the prototype instead:
JSHint won't warn when the function is being assigned.