Non-method functions and this

Kyle Simpson getify at
Mon May 16 09:36:30 PDT 2011

> d) At runtime, a function invoked as a non-method gets a dynamic 
> ReferenceError if it tries to refer to |this|. This would just be kind of 
> obnoxious, I think, since if the function wants to test whether it's been 
> called as a non-method it has to do something like
>    let nonMethod = false;
>    try { eval("this") } catch (e) { nonMethod = true }
> That seems unfortunate.

Couldn't the error only be issued if `this` was used either in an assignment 
fashion (either as an "lvalue" or "rvalue", or de-referenced with the `.` or 
`[]` operators (which should even be statically determinable, right?)?

That way, `typeof this`, `this == undefined`, etc would be safe, as in your 
example above, but ``, `var self = this`, etc would throw a 
ReferenceError error (most would anyway, if `this` was truly `undefined`).

OTOH, it seems like this is more a place for JSLint type assertions rather 
than something to be enforced by the language engine (either at compile-time 
or run-time).

> - and Function.prototype.apply() would have one 
> parameter less.

Yeah, I agree with others that while this might be nice, it would break the 
web (either with compile-time or run-time checking). I always just pass 
`null` for the first param, as I think most people do when it's known that 
`this` isn't going to be used.

It's definitely annoying that in ES3 and ES5 non-strict, such usage will 
still result in `this` defaulting to `window` instead of truly `undefined`.

On a side note, this is also a case where it would be nice if a comma-list 
of parameters to a function call (or array-initialization) could have 
"empty" locations that default to `undefined`, like 
`Function.prototype.apply( ,...)`, but I doubt that'd ever fly. :)



More information about the es-discuss mailing list