Does "use strict" in the constructor extend to prototype methods?
Asked Answered
E

1

6

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?

Educative answered 4/6, 2014 at 10:32 Comment(5)
In a hurry, haven't read this in a while, so I don't know if it has an answer. But seems relevant: ejohn.org/blog/ecmascript-5-strict-mode-json-and-moreGretchen
You might want to look at What does "use strict" do in JavaScript, and what is the reasoning behind it? Basically "use strict" is scoped like ordinary variables within a function.Insomniac
AFAIK "use strict" has literal source code scope and has nothing to do with any inheritance model Javascript has for object methods.Nimocks
Strict mode only applies to the function scope and all that is nested within, which is what the Mozilla code snippet is showing. Prototype methods do not fall within the function scope of their constructor, so I doubt it will inherit it.Tael
How is this a duplicate? The suggested link mentions strict mode but not in the same context!!!Educative
C
5

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;
    }());
    
Colorfast answered 4/6, 2014 at 10:52 Comment(2)
Clear, concise and suggests a good solution. Only thinkg I might have done differently is remove the namespace. Also, worth mentioning that the suggested solution is commonly used in languages that compile to JavaScript like CoffeeScript and TypeScript.Zora
Whar do you mean by "remove the namespace"? For the explanation only? Feel free to edit the code, I'd just revert if I don't like it ;-)Colorfast

© 2022 - 2024 — McMap. All rights reserved.