JSHint "Possible Severe Violation." when using `bind`

Consider this simple code:

"use strict"; var obj = { f: function() { this.prop = 'value'; g.bind( this )(); } }; function g() { console.log( this.prop ); } 

If I try to check this code, jshint gives me a Possible strict violation. error Possible strict violation. where I call console.log( this.prop ); . This is because this undefined is in strict mode in a function.

But I bind this function before calling it, so this is the right object.

I use this “design pattern” to avoid cluttering the main object. Passing properties in parameters also clutters the function, so I refuse to do this. Also, this is exactly what bind for.

Is there a way for JSHint to let me do this?

+69
javascript jshint
Aug 21 2018-12-12T00:
source share
5 answers

It is extremely difficult to detect this case without running the code. You can use the validthis option 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 ); } 

It should be noted that jshint comments are a scope. Thus, the comment will work for the function g and its internal functions, and not just the next line.

+124
Aug 21 '12 at 17:03
source share

You can also achieve the same effect if you change the code to the following to avoid using this all together.

 "use strict"; var obj = { f: function() { this.prop = 'value'; g.bind( null, this )(); } }; function g(self) { console.log( self.prop ); } 
+6
Jun 05 '15 at 15:52
source share

Here's a simpler solution that does not require a template change or special markup for jshint:

 "use strict"; var obj = { f: function() { this.prop = 'value'; G.bind( this )(); } }; function G() { console.log( this.prop ); } 

jshint assumes that you are following a convention in which functions starting with a capital letter are classes to be created and always accessible by this .

+2
Nov 10 '15 at
source share

Try:

 "use strict"; var obj = { f: function() { this.prop = 'value'; g.bind( this )(); } }; var g = function() { console.log( this.prop ); } 
+1
Jun 02 '16 at 11:20
source share

This is another "design template", as you put it, it achieves the same, but completely avoids the problem.

 "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 ); }; 

you will refer to it as follows:

 var myO = new obj(); myO.f(); 
0
Jun 04 '15 at 13:26
source share



All Articles