What is “strict mode” and how is it used?

前端 未结 8 2123
南旧
南旧 2020-12-02 05:42

I\'ve been looking over the JavaScript reference on the Mozilla Developer Network, and I came across something called "strict mode". I read it over an

相关标签:
8条回答
  • 2020-12-02 05:50

    Question:

    Following is the problem I encountered. I was following a tutorial and it ended up trying to compile the following scss file and trying to generate CSS code from it,

    .fatty{
      width: percentage(6/7);
    }
    

    using the following gulpfile.js task:

    var gulp = require('gulp');
    var sass = require('gulp-sass');
    
    gulp.task('sass', function () {
        return gulp.src('app/scss/styles.scss')
            .pipe(sass())
            .pipe(gulp.dest('app/css'))
    });
    

    So the error I'm getting is as follows:

    ~/htdocs/Learning/gulp1/node_modules/gulp-sass/index.js:66
        let sassMap;
        ^^^
    
    SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode
        at exports.runInThisContext (vm.js:53:16)
        at Module._compile (module.js:373:25)
    // stacktrace here...
    

    Solution:

    So it shows me the index.js file which is inside my gulp-sass module (which is basically locked and shouldn't be edited). But if I go forcefully and add the "use_strict" on the top of that index.js file, it runs my task smoothly.

    I was helpless, so I kept using this as the solution! But then after going through some other Stack Overflow Q&As, I saw the following answer as follows:

    sudo npm install -g n
    sudo n stable
    

    And as soon as I updated my Node.js (to version 10.x), and then rebuilt Gulp by running the following commands as Terminal, it instructed me:

    npm rebuild node-sass --force
    

    And it's all okay. So that's how it got resolved. I have undone the changes I did for the index.js Gulp.js module file. And now it runs smoothly.

    0 讨论(0)
  • 2020-12-02 05:53

    2017 and I finally found the documentation:
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode

    Strict mode is a way to opt in to a restricted variant of JavaScript. Strict mode isn't just a subset: it intentionally has different semantics from normal code. Browsers not supporting strict mode will run strict mode code with different behavior from browsers that do, so don't rely on strict mode without feature-testing for support for the relevant aspects of strict mode. Strict mode code and non-strict mode code can coexist, so scripts can opt into strict mode incrementally.


    Strict mode makes several changes to normal JavaScript semantics. First, strict mode eliminates some JavaScript silent errors by changing them to throw errors. Second, strict mode fixes mistakes that make it difficult for JavaScript engines to perform optimizations: strict mode code can sometimes be made to run faster than identical code that's not strict mode. Third, strict mode prohibits some syntax likely to be defined in future versions of ECMAScript.

    0 讨论(0)
  • 2020-12-02 05:54

    Its main purpose is to do more checking.

    Just add "use strict"; at the top of your code, before anything else.

    For example, blah = 33; is valid JavaScript. It means you create a completely global variable blah.

    But in strict mode it's an error because you did not use the keyword "var" to declare the variable.

    Most of the time you don't mean to create global variables in the middle of some arbitrary scope, so most of the time that blah = 33 is written it is an error and the programmer didn't actually want it to be a global variable, they meant to write var blah = 33.

    It similarly disallows a lot of things that are technically valid to do. NaN = "lol" does not produce an error. It also doesn't change the value of NaN. Using strict this (and similar weird statements) produce errors. Most people appreciate this because there is no reason to ever write NaN = "lol", so there was most likely a typo.

    Read more at the MDN page on strict mode.

    0 讨论(0)
  • 2020-12-02 05:55

    One aspect of strict mode not already mentioned in Simon's answer is that strict mode sets this to undefined in functions invoked through function invocation.

    So things like this

    function Obj() {
       this.a = 12;
       this.b = "a";
       this.privilegedMethod = function () {
          this.a++;
          privateMethod();
       };
    
       function privateMethod() {
         this.b = "foo";
       }
    }
    

    will cause an error when privateMethod is called (since you can't add a property to undefined), rather than uselessly adding a b property to the global object.

    0 讨论(0)
  • 2020-12-02 05:58

    ECMAScript 5 introduced the concept of strict mode.

    Invoking Strict Mode in Code

    Strict mode applies to entire scripts or to individual function. It doesn’t apply to block statement enclosed in {} braces, attempting to apply it to such contexts does nothing.

    Entire Script:

    Let’s say we are creating app.js, so adding the first statement use script will enforce strict mode for the entire code.

    // app.js whole script in strict mode syntax
    “use strict”;
    // Now you can start writing your code
    

    Strict mode for function:

    To invoke strict mode for a function, put the exact statement “use strict”; at the start of the function body before any other statement.

    function yourFunc(){
        "use strict";
    
        // Your function code logic
    }
    

    Strict mode incorporate several changes to normal JavaScript semantics. First, strict mode eliminates some JavaScript silent errors by changing them to throw errors.

    For Instance: Code using Strict Mode

    In the above code example, without using strict mode in code, it won't throw an error. As we are accessing variable x without declaring it. So in strict mode accessing undeclared variables throws an error.

    Now let's try to access a variable, x, without declaring it without strict mode.

    (function(){
        x = 3;
    })();
    
    // Will not throw an error
    

    Advantage of using strict mode:

    • Eliminate JavaScript silent errors by throwing errors.
    • Fixes mistakes that make it difficult for JavaScript engine to perform optimisation.
    • Make code sometimes run faster than identical code that’s not in strict mode
    • Prohibits some syntax likely to be defined in future version of ECMAScript.
    0 讨论(0)
  • 2020-12-02 06:08

    ECMAScript5 introduces some new objects and properties and also the so-called "strict mode".

    Strict mode is a subset of the language that excludes deprecated features. The strict mode is opt-in and not required, meaning that if you want your code to run in the strict mode, you declare your intention using (once per function, or once for the whole program) the following string:

    "use strict";
    
    0 讨论(0)
提交回复
热议问题