当使用‘ bind’时,可能存在严格违规

考虑一下这个简单的代码:

"use strict";


var obj = {
f: function() {
this.prop = 'value';
g.bind( this )();
}
};


function g() {
console.log( this.prop );
}

如果我尝试验证这段代码,jshint 会显示错误 Possible strict violation.,在这里我调用 console.log( this.prop );。这是因为 this在函数的严格模式下是未定义的。

但是我在调用它之前绑定了这个函数,所以 this是正确的对象。

我使用这种“设计模式”来避免主要对象混乱。在参数中传递属性也会使函数变得混乱,因此我拒绝这样做。而且,这正是 bind的作用。

JSHint 有办法让我这么做吗?

32430 次浏览

如果不运行代码,就很难检测到这种情况。您可以使用选项 validthis来取消此警告:

"use strict";


var obj = {
f: function() {
this.prop = 'value';
g.bind( this )();
}
};


function g() {
/*jshint validthis:true */
console.log( this.prop );
}

需要注意的是,jshint 注释是函数范围的。因此注释将适用于函数 g及其内部函数,而不仅仅是下一行。

正如您所说的,这是一种不同的“设计模式”,它实现了同样的目标,但是完全避免了问题。

"use strict";


function obj() {
this.prop = '';
}


obj.prototype.f = function obj_f() {
this.prop = 'value';
this.g();
};


obj.prototype.g = function obj_g() {
console.log( this.prop );
};

你可以这样引用它:

var myO = new obj();
myO.f();

如果将代码修改为以下内容以避免同时使用 this,也可以达到同样的效果。

"use strict";


var obj = {
f: function() {
this.prop = 'value';
g.bind( null, this )();
}
};


function g(self) {
console.log( self.prop );
}

这里有一个更简单的解决方案,它不需要对 jshint 的模式或特定标记进行任何更改:

"use strict";


var obj = {
f: function() {
this.prop = 'value';
G.bind( this )();
}
};


function G() {
console.log( this.prop );
}

Jshint 假设您遵循这样的约定,即以大写字母开头的函数是将被实例化的类,并且始终具有可用的 this

试试:

"use strict";


var obj = {
f: function() {
this.prop = 'value';
g.bind( this )();
}
};


var g = function() {
console.log( this.prop );
}