Practical application scenarios
Simplification and Context Binding of Arrow Functions
Arrow functions are one of the most intuitive syntax improvements in ES6. They not only simplify function writing but, more importantly, solve the pain point of this
binding. They are particularly useful in scenarios like event handling and timers:
// Traditional写法
const obj = {
count: 0,
increment: function() {
setInterval(function() {
this.count++; // Here, 'this' points to 'window'
console.log(this.count);
}, 1000);
}
};
// ES6 Arrow Function
const obj = {
count: 0,
increment: function() {
setInterval(() => {
this.count++; // Correctly bound to 'obj'
console.log(this.count);
}, 1000);
}
};
Using arrow functions in array methods makes the code more concise:
const numbers = [1, 2, 3];
const doubled = numbers.map(n => n * 2);
Flexible Use of Destructuring Assignment
Destructuring assignment demonstrates great flexibility in data processing. It appears everywhere from API responses to function parameters:
// Object Destructuring
const response = {
status: 200,
data: {
user: {
id: 123,
name: 'Zhang San'
}
}
};
const {
data: {
user: { id, name }
}
} = response;
// Array Destructuring
const rgb = [255, 128, 64];
const [red, green, blue] = rgb;
// Function Parameter Destructuring
function drawChart({ size = 'big', coords = { x: 0, y: 0 } }) {
console.log(size, coords.x, coords.y);
}
Advanced Usage of Template Literals
Template literals are far more than just string concatenation—they support multiline text and expression interpolation:
// Multiline Text
const htmlTemplate = `
<div class="container">
<h1>${title}</h1>
<p>${content}</p>
</div>
`;
// Tagged Templates
function highlight(strings, ...values) {
return strings.reduce((result, str, i) =>
`${result}${str}<span class="highlight">${values[i] || ''}</span>`, '');
}
const name = 'Li Si';
const age = 28;
highlight`My name is ${name}, and I am ${age} years old`;
Promise and Asynchronous Flow Control
Promises have revolutionized asynchronous programming, and when combined with async/await, they make the code more readable:
// Traditional Callback
fetchData(function(data) {
processData(data, function(result) {
saveResult(result, function() {
console.log('Done');
});
});
});
// Promise Chain
fetchData()
.then(processData)
.then(saveResult)
.then(() => console.log('Done'))
.catch(handleError);
// async/await
async function workflow() {
try {
const data = await fetchData();
const result = await processData(data);
await saveResult(result);
console.log('Done');
} catch (error) {
handleError(error);
}
}
Engineering Practices of Modularization
The ES6 module system laid the foundation for front-end engineering:
// math.js
export const PI = 3.14159;
export function square(x) {
return x * x;
}
// app.js
import { PI, square } from './math.js';
console.log(square(PI));
// Dynamic Import
button.addEventListener('click', async () => {
const module = await import('./dialog.js');
module.openDialog();
});
Class Syntax and Inheritance System
Class syntax makes object-oriented programming in JavaScript more intuitive:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name);
this.breed = breed;
}
speak() {
super.speak();
console.log(`${this.name} barks.`);
}
}
const dog = new Dog('Rex', 'Labrador');
dog.speak();
Spread Operator and Rest Parameters
The ...
operator is extremely practical in array and object operations:
// Array Merging
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2];
// Object Merging
const defaults = { color: 'red', size: 'medium' };
const userSettings = { size: 'large' };
const finalSettings = { ...defaults, ...userSettings };
// Rest Parameters
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
Professional Scenarios for Map/Set Data Structures
When special data structures are needed, Map and Set are more suitable than plain objects:
// Using Map for Key-Value Pairs
const userRoles = new Map();
userRoles.set('user1', 'admin');
userRoles.set('user2', 'editor');
// Using Set for Deduplication
const tags = ['react', 'vue', 'angular', 'react'];
const uniqueTags = new Set(tags);
// Using WeakMap for Private Data
const privateData = new WeakMap();
class Person {
constructor(name) {
privateData.set(this, { name });
}
getName() {
return privateData.get(this).name;
}
}
Special Applications of Iterators and Generators
These features are very powerful when dealing with custom iteration logic:
// Custom Iterator
const fibonacci = {
*[Symbol.iterator]() {
let [prev, curr] = [0, 1];
while (true) {
yield curr;
[prev, curr] = [curr, prev + curr];
}
}
};
for (const n of fibonacci) {
if (n > 1000) break;
console.log(n);
}
// Generator for Asynchronous Flow Control
async function* asyncGenerator() {
const urls = ['/api1', '/api2', '/api3'];
for (const url of urls) {
const response = await fetch(url);
yield response.json();
}
}
for await (const data of asyncGenerator()) {
console.log(data);
}
Metaprogramming with Proxy and Reflect
Implementing advanced interception and custom behaviors:
// Data Validation Proxy
const validator = {
set(target, key, value) {
if (key === 'age' && typeof value !== 'number') {
throw new TypeError('Age must be a number');
}
return Reflect.set(target, key, value);
}
};
const person = new Proxy({}, validator);
person.age = 30; // Works
person.age = 'thirty'; // Throws error
// Proxy for Auto-Filling Dates
const autoDate = {
get(target, key) {
if (key === 'createdAt' && !target[key]) {
return new Date();
}
return target[key];
}
};
const doc = new Proxy({ title: 'New Doc' }, autoDate);
console.log(doc.createdAt); // Auto-fills current date
New Data Types and APIs
ES6 introduced many new native features:
// Binary Array Operations
const buffer = new ArrayBuffer(16);
const view = new Int32Array(buffer);
view[0] = 123456;
// Typed Arrays
const typedArray = new Uint8Array([1, 2, 3, 4]);
// Enhanced Object Literals
const prop = 'name';
const obj = {
[prop]: 'Zhang San', // Computed property names
method() { // Method shorthand
return this[prop];
}
};
Internationalization and Localization Support
The Intl object provides powerful internationalization features:
// Date Formatting
const date = new Date();
console.log(new Intl.DateTimeFormat('zh-CN').format(date));
// Number Formatting
const number = 123456.789;
console.log(new Intl.NumberFormat('de-DE').format(number));
// Relative Time Formatting
const rtf = new Intl.RelativeTimeFormat('zh', { numeric: 'auto' });
console.log(rtf.format(-1, 'day')); // "Yesterday"
Recursive Applications of Tail Call Optimization
Improving recursive performance in specific scenarios:
// Normal Recursion
function factorial(n) {
if (n <= 1) return 1;
return n * factorial(n - 1); // Not a tail call
}
// Tail Recursion Optimization
function factorial(n, acc = 1) {
if (n <= 1) return acc;
return factorial(n - 1, n * acc); // Tail call
}
// Tail-Recursive Fibonacci
function fibonacci(n, a = 0, b = 1) {
if (n === 0) return a;
return fibonacci(n - 1, b, a + b);
}
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
上一篇:集合类型的性能优势
下一篇:Proxy基本创建方式