In Javascript, how can I check if a function is in strict mode * without changing the function *?

I want to write a test suite so that some given functions use strict mode. There are many of them, and manual verification of them seems to be a chorus.

The answer in a similar question uses a regular expression to define a function to test. However, I believe that this will lead to an incorrect determination of situations when the function under test is inside a function with "use strict" or "use strict" at the file level. The answer says that "use strict" is added, but in my environment (Mozilla Rhino) this is not so:

$ cat strict_sub.js "use strict"; var strict_function = function() { not_a_real_global = "foo"; }; print(strict_function); $ rhino strict_sub.js function () { not_a_real_global = "foo"; } 

I feel the answer is no, but is there no way to check the function to see if it has been parsed and strict mode found?

Update. One method suggested by @Amy was to parse the source of the function to figure it out. This works if the function has a strict declaration (although it is tedious), but not if it is a strict mode - it is distributed, say, at the program level; in this case, we must go through the AST to the Program level and check that for use strict . To make this reliable, we would need to implement all the rules for use strict -propagation that the interpreter already has.

(Tested in SpiderMonkey:

 function f() { "use strict"; } var fast1 = Reflect.parse(f.toString()); var first_line = fast1.body[0].body.body[0].expression; print(first_line.type === 'Literal' && first_line.value === 'use strict'); //true 

)

+7
javascript strict
source share
1 answer

Strict mode functions have β€œpoisoned” .caller and .arguments properties (also ES5 , extra ), so you can check this:

 function isStrict(fn) { if (typeof fn != "function") throw new TypeError("expected function"); try { fn.caller; // expected to throw return false; } catch(e) { return true; } } 
+4
source share

All Articles