Does "use strict" in the constructor apply to prototypes?

I am trying to find out if the definition of 'use strict' extends to prototype constructor methods. Example:

var MyNamespace = MyNamespace || {}; MyNamespace.Page = function() { "use strict"; }; MyNamespace.Page.prototype = { fetch : function() { // do I need to use "use strict" here again? } }; 

According to Mozilla, you can use it as:

 function strict(){ "use strict"; function nested() { return "And so am I!"; } return "Hi! I'm a strict mode function! " + nested(); } 

Does this mean that prototype methods inherit strict mode from the constructor?

+6
source share
1 answer

No.

Strict mode applies to all descendant threads (read: nested), but since your fetch function is not created inside the constructor, it is not inherited. You will need to repeat the directive in each of the prototypes.

Privileged methods, by contrast, will be in strict mode when the constructor is in strict mode. To avoid repetition in your case, you can

  • a) make the whole program strict by moving the directive to the first line of the script, or
  • b) wrap your class in an IIFE module and make it strict:

     … = (function() { "use strict"; function Page() { // inherits strictness } Page.prototype.fetch = function() { // inherits strictness }; return Page; }()); 
+5
source

Source: https://habr.com/ru/post/970304/


All Articles