Why does JSHint dislike ternaries for method calls on objects?

后端 未结 3 536
一生所求
一生所求 2021-01-18 03:05

JSHint give the following error:

Expected an assignment or function call and instead saw an expression.

For the following line o

3条回答
  •  北海茫月
    2021-01-18 03:56

    Well, in general it's considered bad practice to call a function using the ternary operator(s), without assigning the return value (which is what you seem to be doing).
    Also, it could be worth checking what JSHint has to say about the following code:

    (aFunctionOrNull || someObject.someMethod)();
    

    If aFunctionOrNull is undefined (or null, or falsy), the logical-or-bit will cause the expression to evaluate to someObject.someMethod, and the resulting value of that is invoked (a reference to a function object, hopefully). This gives you the opportunity to write your code more "fail-safe" without the bulk of a nested ternary:

    (aFunctionOrNull || someObject.someMethod || function(){})();
    

    The grouped expression is now bound to evaluate to a truthy value, so no errors are thrown there.
    To avoid JSHint nagging about your not doing anything with the return value, either assign it to a variable (which I don't really like doing), or add a little operator to the mix:

    ~(aFunctionOrNull || someObject.someMethod || function(){})();//bitwise not
    !(aFunctionOrNull || someObject.someMethod || function(){})();//logical not, doesn't really matter which one
    

    On your last question: someObject.someMethod is indeed a function call. More specifically, it's a call to a function object in the someObject's context.
    For those who don't know this: JS functions are objects, and the called context is either explicitly set using the bind method (defined on the Function.prototype) or ad-hoc:

    var referenceToMethod = someObject.someMethod;
    referenceToMethod();//<-- inside the function objects, this now points to the global object
    

    An easy way to think of it is that JS functions just float around aimlessly in memory/space/time, until they are called via a reference, the context of that reference is then passed to the function object, to determine what object it'll interact with. This is, sadly, the global object by default, or null in strict mode.

提交回复
热议问题