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

女生的网名这么多〃 提交于 2019-11-28 08:03:37

问题


I'm trying to figure out whether the definition of 'use strict' extends to the prototype methods of the constructor. 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 it mean that prototype methods inherit strict mode from the constructor?


回答1:


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;
    }());
    


来源:https://stackoverflow.com/questions/24035111/does-use-strict-in-the-constructor-extend-to-prototype-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!