Flo*_*ine 73 javascript jshint
考虑这个简单的代码:
"use strict";
var obj = {
f: function() {
this.prop = 'value';
g.bind( this )();
}
};
function g() {
console.log( this.prop );
}
Run Code Online (Sandbox Code Playgroud)
如果我尝试验证此代码,jshint会Possible strict violation.
在我调用时给出错误console.log( this.prop );
.这是因为this
在函数中严格模式下未定义.
但是我在调用它之前绑定了这个函数,所以它this
是正确的对象.
我正在使用这种"设计模式"来避免使主要对象混乱.传递参数中的属性也会使函数混乱,所以我拒绝这样做.此外,这正是bind
为了什么.
有没有办法让JSHint让我这样做?
Ant*_*yov 128
没有运行代码就很难检测到这种情况.您可以使用选项validthis
来禁止此警告:
"use strict";
var obj = {
f: function() {
this.prop = 'value';
g.bind( this )();
}
};
function g() {
/*jshint validthis:true */
console.log( this.prop );
}
Run Code Online (Sandbox Code Playgroud)
需要注意的是,jshint注释是函数作用域.因此注释将适用于函数g
及其内部函数,而不仅仅是下一行.
如果将代码修改为以下代码以避免this
全部使用,也可以实现相同的效果.
"use strict";
var obj = {
f: function() {
this.prop = 'value';
g.bind( null, this )();
}
};
function g(self) {
console.log( self.prop );
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
32229 次 |
最近记录: |