Does “use strict” in the constructor extend to prototype methods?

后端 未结 1 1920
谎友^
谎友^ 2020-12-20 20:49

I\'m trying to figure out whether the definition of \'use strict\' extends to the prototype methods of the constructor. Example:

var MyNamespace = MyNamespac         


        
相关标签:
1条回答
  • 2020-12-20 21:17

    No.

    Strict mode does extend to all descendant (read: nested) scopes, but since your fetch function is not created inside the constructor it is not inherited. You would need to repeat the directive in each of the prototype methods.

    Privileged methods in contrast would 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 a module IIFE, and make that strict:

      … = (function() {
          "use strict";
      
          function Page() {
              // inherits strictness
          }
          Page.prototype.fetch = function() {
              // inherits strictness
          };
          return Page;
      }());
      
    0 讨论(0)
提交回复
热议问题