scusyxx
scusyxx

Reputation: 1244

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";
    // Body
}

function b(){
// Body
}

function isStrict(fn){

    fn.call();
}

isStrict(a); // true
isStrict(b); // false

Upvotes: 0

Views: 149

Answers (2)

Rob W
Rob W

Reputation: 349042

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

function isStrict(fn) {
    return typeof fn == 'function' &&
        /^function[^(]*\([^)]*\)\s*\{\s*(["'])use strict\1/.test(fn.toString())
        || (function(){ return this === 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.

Upvotes: 3

Will
Will

Reputation: 20235

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

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

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

Upvotes: 1

Related Questions