質問

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 its this will 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 its this is not set, so in non–strict mode this will be set to the global object so this.e = ... references (or creates due to the assignment) a global e property.

However, in strict mode this will 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:

var _snr = (function(global) {
    return function (id) {
        global.e = "something";
    };
}(this));

In non-strict mode, you can do:

function _snr(id) {
    var global = (function(){return this;}());
    global.e = "something";
}

so that global within 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:

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?

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).

What "use strict" is actually doing

It is stopping this being set to the global object if the call sets it to undefined or null. See above for the consequence of that.

and how I can fix my code?

See above.

Oh, and finally, there is an informative summary of strict mode in ECMA-262 Annex C The Strict Mode of ECMAScript.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top