Skip to content Skip to sidebar Skip to footer

Is It Possible To Tell Whether A Function Is In Strict Mode Or Not?

My question may sound weird but is there a way to understand whether a function is in strict mode or not by calling from another function? function a(){ 'use strict'; // Bo

Solution 1:

When a function is affected by strict mode, "use strict"; is prepended. So, the following check would be OK:

functionisStrict(fn) {
    returntypeof fn == 'function' &&
        /^function[^(]*\([^)]*\)\s*\{\s*(["'])use strict\1/.test(fn.toString())
        || (function(){ returnthis === undefined;})();
}

I used a RegExp to look for the "use strict" pattern at the beginning of the function's body.

To detect the global strict mode (which also affects a function), I'd test one of the features to see whether strict mode is active.

Solution 2:

You could add an isStrict property to each function you make strict.

function a() {
    "use strict";
}
a.isStrict = true;

// ...if ( a.isStrict ) { }

Post a Comment for "Is It Possible To Tell Whether A Function Is In Strict Mode Or Not?"