Modern JavaScript Tutorial (Chinese Translation)

repository·master·Indexed 27 days ago

https://github.com/javascript-tutorial/zh.javascript.info

The Chinese translation of the Modern JavaScript Tutorial, a comprehensive resource for learning JavaScript supported by React and MDN. The documentation covers JavaScript engines, browser capabilities and security, transpiled languages like TypeScript and Flow, and practical guides on using developer tools, IDEs, and the ECMA-262 specification.

Tokens
193.1K
Snippets
471
Records
1.2K
Agent score
95%

What's inside zh.javascript.info

  1. Understand JavaScript Engines and Execution

    master

    JavaScript is executed by an engine (often called a JavaScript Virtual Machine) embedded in the environment (like a browser). The engine follows a three-step process:

    1. Parsing: The engine reads the script.
    2. Compilation: The engine converts the script into machine language.
    3. Execution: The machine code is executed rapidly.

    Common JavaScript engines include:

    • V8: Used in Chrome, Opera, and Edge.
    • SpiderMonkey: Used in Firefox.
    • JavaScriptCore/Nitro/SquirrelFish: Used in Safari.
    • Chakra: Used in IE.
  2. Summary of String Operations and Methods

    master

    JavaScript strings use UTF-16 encoding. Key operations include:

    • Quotes: Three types of quotes are available. Backticks (`) allow multi-line strings and expression interpolation using ${...}.
    • Special Characters: Use escape sequences like \n or Unicode escapes like \u....
    • Accessing Characters: Use bracket notation [] to access characters by index.
    • Substrings: Use slice or substring to extract parts of a string.
    • Case Conversion: Use toLowerCase() and toUpperCase().
    • Searching: Use indexOf() for position, or includes(), startsWith(), and endsWith() for boolean checks.
    • Comparison: Use localeCompare() for language-sensitive comparison; otherwise, strings are compared by character codes.
    • Trimming: Use trim() to remove whitespace from both ends.
    • Repetition: Use repeat(n) to repeat a string n times.
  3. How the Execution Context Stack works with Recursion

    master

    When a function performs a nested call (recursion), the JavaScript engine manages the execution using an Execution Context Stack:

    1. The current function is paused.
    2. Its Execution Context (containing current variables, control flow position, etc.) is saved onto the top of the stack.
    3. The nested call is executed, creating a new context on top.
    4. Once the nested call finishes, its context is removed from the stack, and the previous context is restored from the stack, resuming execution from exactly where it left off.

    The recursion depth is equal to the maximum number of contexts present in the stack at any one time.

  4. Understand Behavior-Driven Development (BDD) with Mocha

    master
    Behavior-Driven Development (BDD) is a technique that combines tests, documentation, and examples. In a BDD workflow, you write a specification (spec)—a description of how a function should behave—before writing the actual implementation. This process is iterative: write a spec, implement the code, run tests, and refine both until the feature is complete.
  5. Understand the DOM Tree structure

    master

    The Document Object Model (DOM) represents an HTML document as a tree of objects. Every HTML tag is an object, and nested tags are 'children' of their parent tags. Text within tags also becomes an object. You can access and modify these objects using JavaScript to change the page content or style.

    Common properties for accessing nodes include:

    • innerHTML: The HTML content of a node.
    • style.background: Used to modify the CSS background of an element.
    • offsetWidth: The width of a node in pixels.
  6. Understand the position of 'document' in the DOM hierarchy

    master
    In the DOM hierarchy, document is a special object that serves as the entry point to the document tree. It is not an Element or an HTMLElement. Instead, it is an instance of the Document interface, which inherits from Node. It represents the entire web page and acts as the root of the document tree.
  7. Understand the Same-Origin Policy

    master

    The Same-Origin Policy (SOP) restricts how windows and frames can interact. Two URLs are considered to have the same origin if they share the same protocol, domain, and port.

    Same Origin Examples:

    • http://site.com
    • http://site.com/
    • http://site.com/my/page.html

    Different Origin Examples:

    • http://www.site.com (different domain due to www.)
    • http://site.org (different domain)
    • https://site.com (different protocol)
    • http://site.com:8080 (different port)

    Access Rules:

    • Same-Origin: You have full access to variables, documents, and content of the other window.
    • Cross-Origin: You cannot read variables, documents, or the location.href. However, you can write to location (e.g., redirecting the user).
  8. Understand JavaScript Garbage Collection and Reachability

    master

    JavaScript memory management is automatic. The engine uses the concept of reachability to determine which values can be kept in memory and which should be cleared.

    Roots

    "Roots" are the starting points for reachability. They include:

    • The currently executing function and its local variables/parameters.
    • Other functions in the current nested call chain and their variables.
    • Global variables.

    Reachability Rules

    • A value is reachable if it can be accessed from the roots via a reference or a chain of references.
    • A value is unreachable if there is no path from any root to that value. Unreachable values are considered garbage and will be removed by the garbage collector.

    Key Behaviors

    • Multiple References: An object remains in memory as long as at least one reachable variable points to it.
    • Circular References (Islands): A group of objects might reference each other (forming a cycle), but if the entire group is disconnected from the roots, the whole group is considered an "unreachable island" and will be garbage collected.
  9. Understand the differences between `var` and `let/const`

    master

    When migrating from legacy scripts or working with older codebases, it is critical to understand that var behaves differently than let and const. The two primary differences are:

    1. Scope: var does not have block scope. It is either function-scoped or globally scoped. It ignores blocks like if or for.
    2. Hoisting: var declarations are processed at the beginning of the function (or script), meaning they are 'hoisted' to the top, though assignments are not.

    In modern JavaScript, always prefer let and const to avoid these behaviors.

  10. Understand Shadow DOM encapsulation rules

    master

    Shadow DOM provides strong encapsulation through the following behaviors:

    1. DOM Isolation: Elements inside a Shadow DOM are invisible to standard document selectors like document.querySelector. To find them, you must query from within the shadow root (e.g., elem.shadowRoot.querySelector).
    2. Style Isolation: External CSS rules from the main document do not apply to elements inside the Shadow DOM. Conversely, styles defined inside the Shadow DOM only affect its internal elements.
    3. ID Namespace: The Shadow DOM has its own unique ID space, meaning IDs inside the shadow tree do not conflict with IDs in the light DOM.
  11. Use EventSource for Server-Sent Events (SSE)

    master

    The EventSource interface allows a client to establish a persistent, one-way connection to a server to receive real-time updates. Unlike WebSockets, SSE is unidirectional (server-to-client only) and uses standard HTTP. It is ideal for data streams like chat messages or market prices and includes built-in automatic reconnection support.

    let eventSource = new EventSource("/events/subscribe");
    
    eventSource.onmessage = function(event) {
      console.log("New message", event.data);
    };
  12. Understand Cross-Origin Resource Sharing (CORS)

    master

    When making fetch requests to a different origin (a combination of domain, port, and protocol), the request may fail unless the remote server explicitly allows it via CORS (Cross-Origin Resource Sharing).

    To enable cross-origin access, the server must include the Access-Control-Allow-Origin header in its response. This header can contain the specific origin (e.g., https://javascript.info) or a wildcard * to allow any origin.

    try {
      await fetch('http://example.com');
    } catch(err) {
      alert(err); // fetch fails if CORS is not configured on example.com
    }