Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
491 views
in Technique[技术] by (71.8m points)

javascript - Does "use strict" in the constructor extend to prototype methods?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...