for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100); // 输出3, 3, 3
}
// 使用let解决
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100); // 输出0, 1, 2
}
if (true) {
let x = 10;
}
console.log(x); // 报错:x is not defined
// 传统函数组件
function Button(props) {
return <button onClick={props.onClick}>{props.label}</button>;
}
// 箭头函数组件
const Button = (props) => (
<button onClick={props.onClick}>{props.label}</button>
);
// 简化参数解构
const Button = ({ onClick, label }) => (
<button onClick={onClick}>{label}</button>
);
// map方法
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(num => num * 2); // [2, 4, 6, 8]
// filter方法
const evenNumbers = numbers.filter(num => num % 2 === 0); // [2, 4]
// reduce方法
const sum = numbers.reduce((acc, num) => acc + num, 0); // 10
// i18n.js
export const translations = {
en: {
greeting: 'Hello, {name}!',
welcome: 'Welcome to our website.'
},
fr: {
greeting: 'Bonjour, {name}!',
welcome: 'Bienvenue sur notre site web.'
}
};
export const t = (key, params = {}) => {
const language = localStorage.getItem('language') || 'en';
let message = translations[language][key] || key;
return Object.keys(params).reduce((acc, param) => {
return acc.replace(`{${param}}`, params[param]);
}, message);
};
// highlight.js
export const highlight = (strings, ...values) => {
let result = '';
strings.forEach((string, i) => {
result += string;
if (i < values.length) {
result += `<span class="highlight">${values[i]}</span>`;
}
});
return result;
};
// 从props中解构并设置默认值
const UserProfile = ({
user: {
name = 'Guest',
age = 0,
address: { city = 'Unknown' } = {}
} = {}
}) => (
<div>
<p>Name: {name}</p>
<p>Age: {age}</p>
<p>City: {city}</p>
</div>
);
// 函数参数解构
const calculateArea = ({ width, height }) => {
return width * height;
};
const rect = { width: 10, height: 5 };
console.log(calculateArea(rect)); // 50
// 组件默认参数
const Card = ({
title = 'Default Title',
content = 'Default Content',
style = {}
}) => (
<div className="card" style={{ ...style, border: '1px solid #ccc' }}>
<h3>{title}</h3>
<p>{content}</p>
</div>
);
// withLoading高阶组件
const withLoading = (Component) => {
return ({ isLoading, ...props }) => {
if (isLoading) {
return <div>Loading...</div>;
}
return <Component {...props} />;
};
};
// 使用高阶组件
const LoadingButton = withLoading(Button);
// BaseComponent.js
export class BaseComponent {
constructor(props) {
this.props = props;
this.state = {};
}
setState(newState) {
this.state = { ...this.state, ...newState };
this.render();
}
render() {
// 子类实现
}
}
// ButtonComponent.js
import { BaseComponent } from './BaseComponent';
export class ButtonComponent extends BaseComponent {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
if (this.props.onClick) {
this.props.onClick();
}
}
render() {
return `
<button onclick="${this.handleClick}">
${this.props.label || 'Click me'}
</button>
`;
}
}
// api.js
export const fetchData = async (url, options = {}) => {
try {
const response = await fetch(url, {
method: options.method || 'GET',
headers: {
'Content-Type': 'application/json',
...options.headers
},
body: options.body ? JSON.stringify(options.body) : null
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error('Fetch error:', error);
throw error;
}
};
// retry.js
export const withRetry = (fn, maxRetries = 3) => {
return async (...args) => {
let retries = 0;
while (retries < maxRetries) {
try {
return await fn(...args);
} catch (error) {
retries++;
if (retries >= maxRetries) {
throw error;
}
console.log(`Retry ${retries} in ${retries * 1000}ms`);
await new Promise(resolve => setTimeout(resolve, retries * 1000));
}
}
};
};
// 使用重试机制
const fetchWithRetry = withRetry(fetchData, 3);
src/
components/
Button/
index.js
Button.vue
Button.test.js
utils/
index.js
math.js
string.js
api/
index.js
user.js
product.js
store/
index.js
userStore.js
productStore.js
// utils/index.js
export * from './math.js';
export * from './string.js';
export * from './date.js';
// 使用
import { add, multiply } from '../utils';
// 安全获取嵌套对象属性
const getUserCity = (user) => {
return user?.address?.city ?? 'Unknown';
};
// 使用
const user = { name: 'John' };
console.log(getUserCity(user)); // 'Unknown'
// 按需加载组件
const loadHeavyComponent = async () => {
const HeavyComponent = await import('./HeavyComponent.vue');
return HeavyComponent.default;
};
// 在组件中使用
export default {
components: {
HeavyComponent: () => loadHeavyComponent()
}
};
ES6新特性为JavaScript开发带来了极大的便利,通过合理的封装和应用,可以显著提升代码的可读性、可维护性和开发效率。关键应用包括:
通过本文提供的封装方法和应用实例,开发者可以更好地利用ES6特性构建高质量的JavaScript应用。
ES6 新特性,ECMAScript 6,let,const, 箭头函数,模板字符串,解构赋值,Promise,Class 类,模块化,组件封装,JavaScript, 前端开发,Web 开发,热门技术
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。