阿里云主机折上折
  • 微信号
Current Site:Index > Strict mode translates this sentence into English.

Strict mode translates this sentence into English.

Author:Chuan Chen 阅读数:34392人阅读 分类: JavaScript

The Concept of Strict Mode

Strict mode is a special execution mode introduced in ECMAScript 5 that makes code safer and more optimized by restricting certain syntax features and throwing more errors. In strict mode, the JavaScript engine performs stricter syntax checks and disables some deprecated features.

// Ways to enable strict mode
'use strict';

function strictFunction() {
    'use strict';
    // Strict mode code within the function
}

Key Changes in Strict Mode

Variable Declaration Requirements

In strict mode, all variables must be explicitly declared; otherwise, a ReferenceError is thrown.

'use strict';
x = 10; // ReferenceError: x is not defined
let y = 20; // Correct declaration

Prohibiting Deletion of Non-Configurable Properties

Strict mode prohibits deleting variables, functions, or non-configurable properties.

'use strict';
var obj = {};
Object.defineProperty(obj, 'x', { value: 42, configurable: false });
delete obj.x; // TypeError: Cannot delete property 'x' of #<Object>

Function Parameter Restrictions

In strict mode, function parameters cannot have duplicate names, and the behavior of the arguments object is modified.

'use strict';
function duplicateParams(a, a) { // SyntaxError: Duplicate parameter name not allowed
    // ...
}

Changes to this Value

In non-strict mode, this in global functions points to the window object, whereas in strict mode, this is undefined.

'use strict';
function showThis() {
    console.log(this); // undefined
}
showThis();

Restrictions on eval and arguments in Strict Mode

Independent Scope for eval

In strict mode, variables created by eval do not leak into the outer scope.

'use strict';
eval('var x = 10;');
console.log(x); // ReferenceError: x is not defined

arguments No Longer Bound to Parameters

In strict mode, the arguments object does not dynamically reflect parameter changes.

'use strict';
function func(a) {
    a = 2;
    console.log(a, arguments[0]); // 2, 1
}
func(1);

Other Restrictions in Strict Mode

Prohibition of Octal Literals

Strict mode disallows the use of octal numeric literals.

'use strict';
var num = 010; // SyntaxError: Octal literals are not allowed

Prohibiting Extension of Non-Extensible Objects

In strict mode, new properties cannot be added to non-extensible objects.

'use strict';
var obj = {};
Object.preventExtensions(obj);
obj.newProp = 'value'; // TypeError: Cannot add property newProp, object is not extensible

Security Features in Strict Mode

Prohibition of with Statements

Strict mode disables with statements due to performance issues and scope confusion.

'use strict';
with (obj) { // SyntaxError: Strict mode code may not include a with statement
    // ...
}

Restricting Access to caller and callee

In strict mode, accessing the caller and callee properties of functions is prohibited.

'use strict';
function restricted() {
    return restricted.caller; // TypeError: 'caller' and 'arguments' are restricted
}

Practical Applications of Strict Mode

Strict Mode in Module Systems

Modern JavaScript module systems (e.g., ES6 modules) automatically operate in strict mode.

// ES6 modules automatically enable strict mode
export function example() {
    undeclaredVar = 1; // ReferenceError
}

Strict Mode in Class Declarations

All code within ES6 class declarations automatically runs in strict mode.

class StrictClass {
    constructor() {
        undeclared = 1; // ReferenceError
    }
}

Performance Benefits of Strict Mode

Strict mode enables more optimizations by eliminating certain dynamic features.

'use strict';
function optimized() {
    // The engine can optimize this function better
    // because it knows there will be no dynamic scope lookups
    let x = 10;
    return x * 2;
}

Compatibility Considerations for Strict Mode

While strict mode is widely supported in modern browsers, caution is needed when using it in older environments.

// Detecting strict mode support
var isStrictSupported = (function() {
    'use strict';
    return !this;
})();

Best Practices for Strict Mode

Gradual Migration to Strict Mode

Large projects can adopt strict mode incrementally, starting with individual files or functions.

// Non-strict code
function legacyCode() {
    // Legacy code
}

// New code uses strict mode
'use strict';
function newCode() {
    // Strict mode code
}

Using Tools

Use linter tools (e.g., ESLint) to ensure strict mode rules are followed correctly.

// .eslintrc.js
module.exports = {
    rules: {
        strict: ['error', 'global']
    }
};

Strict Mode and Future JavaScript Features

Many new JavaScript features require or recommend strict mode.

'use strict';
// Class field declarations
class FutureReady {
    field = 123; // Requires strict mode
}

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.