引言
ECMAScript 2015(ES6)注入了JavaScript全新的活力,提供了许多高级技巧,使得代码更加精炼和灵活。在这篇文章中,我们将深入探讨一系列令人惊叹的ES6高级技巧,为你打开JavaScript的魔法之门。
1. 高级解构赋值
1.1 默认值和重命名
const person = { name: 'John' };
const { name: fullName = 'Guest' } = person;
console.log(fullName); // 'John'
1.2 解构函数参数
function printUser({ name, age }) {
console.log(`${name} is ${age} years old.`);
}
const user = { name: 'John', age: 30 };
printUser(user); // 'John is 30 years old.'
2. Symbol 和迭代器
2.1 Symbol
const mySymbol = Symbol('unique');
const obj = {
[mySymbol]: 'I am a symbol'
};
console.log(obj[mySymbol]); // 'I am a symbol'
2.2 自定义迭代器
const iterableObject = {
data: [1, 2, 3],
[Symbol.iterator]() {
let index = 0;
return {
next: () => ({
value: this.data[index++],
done: index > this.data.length
})
};
}
};
for (const value of iterableObject) {
console.log(value); // 1, 2, 3
}
3. Map 和 Set 的高级用法
3.1 Map 的链式调用
const userMap = new Map()
.set('name', 'John')
.set('age', 30);
console.log(userMap.get('name')); // 'John'
3.2 Set 的交集、并集、差集
const set1 = new Set([1, 2, 3]);
const set2 = new Set([3, 4, 5]);
const intersection = new Set([...set1].filter(value => set2.has(value)));
const union = new Set([...set1, ...set2]);
const difference = new Set([...set1].filter(value => !set2.has(value)));
console.log(intersection); // Set { 3 }
console.log(union); // Set { 1, 2, 3, 4, 5 }
console.log(difference); // Set { 1, 2 }
4. Proxies
4.1 基本使用
const handler = {
get: function(target, prop) {
return prop in target ? target[prop] : 'Not found';
}
};
const person = new Proxy({ name: 'John' }, handler);
console.log(person.name); // 'John'
console.log(person.city); // 'Not found'
4.2 拦截器方法
const validator = {
set: function(obj, prop, value) {
if (prop === 'age' && !Number.isInteger(value)) {
throw new TypeError('Age must be an integer.');
}
obj[prop] = value;
return true;
}
};
const person = new Proxy({}, validator);
person.age = 30; // Valid
person.age = 'thirty'; // Throws TypeError
5. 手写Promise:异步魔法的奇迹
class MyPromise {
constructor(executor) {
this.state = 'pending';
this.value = undefined;
this.reason = undefined;
const resolve = value => {
if (this.state === 'pending') {
this.state = 'fulfilled';
this.value = value;
}
};
const reject = reason => {
if (this.state === 'pending') {
this.state = 'rejected';
this.reason = reason;
}
};
try {
executor(resolve, reject);
} catch (error) {
reject(error);
}
}
then(onFulfilled, onRejected) {
if (this.state === 'fulfilled') {
onFulfilled(this.value);
} else if (this.state === 'rejected') {
onRejected(this.reason);
}
}
}
// 使用示例
const promise = new MyPromise((resolve, reject) => {
// 异步操作...
resolve('Success!');
});
promise.then(value => console.log(value)); // 'Success!'
通过这篇文章,让我们一同揭开ES6的高级技巧面纱,掌握JavaScript的魔法,让你的代码更为精妙和富有表现力。