I am defining the following function in my JavaScript:
function _snr(id) {
"use strict";
this.e = "something";
}
I ran my code through JSLint and it suggested that I add “use strict” to the function.
When I do e now throws and undefined error. From some initial investigation it looks as though this which used to refer to _snr is no longer defined.
I have read about “use strict” and discovered that it is used to prevent unsafe practices. Could some one explain what was unsafe about this? What “use strict” is actually doing and how I can fix my code?
If a function is called without setting its
this, in non–strict mode itsthiswill be set to reference the global (window in a browser) object. In strict mode, it wil remain undefined.If your function is called as
_snr(...)then itsthisis not set, so in non–strict modethiswill be set to the global object sothis.e = ...references (or creates due to the assignment) a globaleproperty.However, in strict mode
thiswill be undefined, and trying to access a property of undefined throws an error.It’s explained in ECMA-262 §10.4.3 Entering Function Code.
Edit
If you wish to access the global object from inside a function in a manner that is consistent with both strict and non–strict mode, you can use something like:
In non-strict mode, you can do:
so that
globalwithin the function references the global object and you don’t have to worry about how the function is called. But the second example won’t work in strict mode.Other answers:
Absolutely nothing in this particular case.
However, in a more general case, it was considered a good idea to be able to execute code within a context that stopped it accessing the global object directly. The second example above shows how that can be done in non–strict code (i.e. how you can get direct access to the global object from inside a function context).
It is stopping
thisbeing set to the global object if the call sets it toundefinedornull. See above for the consequence of that.See above.
Oh, and finally, there is an informative summary of strict mode in ECMA-262 Annex C The Strict Mode of ECMAScript.