Yuan-YY Programming Notes
website·Indexed 29 days ago
https://yuan-yy.github.io/vuepress2.4/A comprehensive collection of technical notes and tutorials covering TypeScript basics and advanced features (generics, declaration merging, type inference), refactoring techniques (inheritance, extracting functions), and frontend development with Vue, CSS, and JavaScript.
What's inside Yuan-YY Knowledge Base
- Before modifying any code during refactoring, the first essential step is to ensure the code has a set of reliable automated tests. This prevents the introduction of bugs and ensures that the system's behavior remains consistent as the internal structure is improved.
Respond to route changes using $route watcher
The$routeobject contains information about the current route. You can watch this object to trigger logic when the route changes.watch: { '$route'(to, from) { // Respond to route changes console.log('Current route info:', to); console.log('Previous route info:', from); } }Use Type Assertions to manually specify a value's type
Type assertions are used to tell the TypeScript compiler that a value is of a specific type, effectively overriding the compiler's inferred type. This is useful when the developer has more specific information about the type than TypeScript can determine statically.// Recommended syntax (required in TSX/React) const value = someValue as TargetType; // Alternative syntax (not recommended for TSX) const value = <TargetType>someValue;Use HTML Meta tags for SEO and page description
Use<meta>tags within the HTML head to provide metadata about the page for search engines and browsers.<!-- Describe page keywords --> <meta name="keywords" content="keyword1, keyword2, keyword3"> <!-- Describe the page content --> <meta name="description" content="HTML examples">Understand Chrome's multi-process architecture
Chrome uses a multi-process architecture to improve stability and security. Opening a single page typically requires at least four processes:
- Browser Process: Manages the UI, user interaction, child processes, and storage.
- Rendering Process: Converts HTML, CSS, and JavaScript into an interactive webpage. It runs the Blink layout engine and V8 JavaScript engine. By default, Chrome creates one rendering process per tab (sandboxed for security).
- GPU Process: Handles GPU-accelerated drawing for the browser UI and web content (e.g., 3D CSS).
- Network Process: Responsible for loading network resources.
- Plugin Process: Isolates plugins to prevent plugin crashes from affecting the rest of the browser.
Understand TypeScript core characteristics
TypeScript is a statically typed, weakly typed language that adds a type system to JavaScript. Key characteristics include:
- Full JavaScript Compatibility: It does not modify JavaScript runtime behavior and is fully compatible with JS.
- Compilation: TypeScript compiles to JavaScript, allowing it to run in any JS environment (Browsers, Node.js, etc.).
- Gradual Migration: It can coexist with JavaScript, enabling projects to migrate to TypeScript incrementally.
- Configurable Strictness: It provides various compilation options to control the level of type-checking strictness.
- IDE Enhancement: It improves developer experience by providing code completion, interface hints, 'go to definition', and refactoring tools.
- Standard Alignment: It evolves in sync with the latest ECMAScript standards (Stage 3).
Manage execution contexts using the Call Stack
The JavaScript engine uses a Call Stack (a LIFO - Last In, First Out structure) to manage execution contexts.
Execution contexts are created and pushed onto the stack in these scenarios:
- Global code execution: Creates a single global execution context for the page lifecycle.
- Function calls: Creates a function execution context, which is popped off the stack once the function returns.
eval()calls: Compiles the code and creates a new execution context.
If the number of pushed contexts exceeds the stack limit, a 'Stack Overflow' error occurs.
Leverage refactoring to improve software quality and velocity
Refactoring serves as a tool to achieve several critical software engineering goals:
- Improve Software Design: Prevents architectural decay. By eliminating duplicate code, it ensures that every behavior is represented once, making future modifications easier and safer.
- Enhance Readability: Bridges the gap between 'what I want the code to do' and 'what I told the computer to do,' making the code's intent clear for future maintainers (including the original author).
- Facilitate Bug Detection: The process of restructuring forces a deeper understanding of the code, which often reveals hidden bugs and validates assumptions about how the program works.
- Increase Programming Speed: While it seems slower to take small steps, the lack of debugging time and the improved clarity of the codebase lead to faster overall development velocity.
Declare global variables using declare var, let, and const
Use
declarestatements to tell the TypeScript compiler about variables that exist in the global scope (e.g., loaded via a<script>tag).declare varordeclare let: Defines a global variable that can be reassigned.declare const: Defines a global variable as a constant that cannot be reassigned.
Note: Declaration statements must only define the type; they cannot contain the actual implementation.
// Allow reassignment declare let jQuery: (selector: string) => any; // Prevent reassignment (Recommended for most global libs) declare const jQuery: (selector: string) => any;Convert a Reference Object to a Value Object
Convert an internal object from a reference object (where properties are updated in place) to a value object (where the entire object is replaced upon change). Value objects are immutable, making them easier to reason about, safer to pass around, and ideal for distributed or concurrent systems.
Steps to implement:
- Ensure the target object is immutable or can be made immutable.
- Remove all setter functions (Remove Setter).
- Implement a value-based equality check (e.g., an
equalsmethod) instead of relying on reference equality. - Update callers to replace the entire object instance when a change is needed.
// 1. Make the class immutable class TelephoneNumber { constructor(areaCode, number) { this._areaCode = areaCode; this._number = number; } get areaCode() { return this._areaCode; } get number() { return this._number; } // 2. Implement value-based equality equals(other) { if (!(other instanceof TelephoneNumber)) return false; return this.areaCode === other.areaCode && this.number === other.number; } } class Person { constructor() { this._telephoneNumber = new TelephoneNumber(); } // 3. Replace the whole object instead of mutating properties set officeAreaCode(arg) { this._telephoneNumber = new TelephoneNumber(arg, this.officeNumber); } }Benefits of using TypeScript for project development
TypeScript improves code readability and maintainability by providing a type system that serves as living documentation. Key advantages include:
- Early Error Detection: Most errors are caught during the compilation phase rather than at runtime.
- Enhanced IDE Support: Provides superior code completion, interface hints, 'jump to definition' navigation, and safer code refactoring.
- Scalability: While beneficial for large-scale projects and multi-person collaboration, it is recommended for most projects to reduce bug rates and increase development efficiency.
Understand Chrome browser process architecture
A web page requires at least four types of processes to function in Chrome:
- Browser Process: Responsible for UI display, user interaction, child process management, and storage functions.
- Renderer Process: Converts HTML, CSS, and JavaScript into an interactive webpage. This process hosts the Blink layout engine and the V8 JavaScript engine. By default, Chrome creates a renderer process for each site.