JSHint“可能严格违规。”当使用`bind`时 [英] JSHint "Possible strict violation." when using `bind`
问题描述
考虑这个简单的代码:
"use strict";
var obj = {
f: function() {
this.prop = 'value';
g.bind( this )();
}
};
function g() {
console.log( this.prop );
}
如果我尝试验证此代码,jshint会给我错误可能严格违规。
我在哪里调用 console.log(this.prop);
。这是因为这个
在函数的严格模式下是未定义的。
If I try to validate this code, jshint gives me the error Possible strict violation.
where I call console.log( this.prop );
. This is because this
is undefined in strict mode in a function.
但我在调用之前绑定了这个函数它,所以这个
是正确的对象。
But I'm binding this function before calling it, so this
is the correct object.
我正在使用这种设计模式来避免混乱主要对象。传递参数中的属性也会使函数混乱,所以我拒绝这样做。此外,这正是 bind
的用途。
I'm using this "design pattern" to avoid cluttering the main object. Passing the properties in the parameters will also clutter the function, so I refuse to do this. Besides, this is exactly what bind
is for.
JSHint是否有办法让我这样做?
Is there a way for JSHint to let me do this?
推荐答案
如果不运行代码,很难检测到这种情况。您可以使用选项 validthis
来取消此警告:
It is extremely hard to detect this case without running the code. You can use option validthis
to suppress this warning:
"use strict";
var obj = {
f: function() {
this.prop = 'value';
g.bind( this )();
}
};
function g() {
/*jshint validthis:true */
console.log( this.prop );
}
需要注意的是,jshint注释是函数作用域。因此评论将适用于函数 g
及其内部函数,而不仅仅是下一行。
It is to be noted that jshint comments are function scoped. So the comment will work for the function g
and its inner functions, not just the next line.
这篇关于JSHint“可能严格违规。”当使用`bind`时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!