1. 对象属性简写
1.1 基本语法
const name = 'John';
const age = 25;
const user = {name: name,age: age
};
const user = {name,age
};
1.2 实际应用场景
function createUser(name, age, email) {return {name,age,email};
}
function useState(initialState) {const state = initialState;const setState = (newState) => {};return { state, setState };
}
const actions = {increment,decrement,reset
};
export default actions;
2. 对象属性表达式
2.1 基本语法
const prefix = 'user';
const id = 1;
const user = {[`${prefix}_${id}`]: 'John',[`${prefix}Email`]: 'john@example.com'
};console.log(user.user_1);
console.log(user.userEmail);
2.2 实际应用场景
function createStyles(theme) {return {[`button_${theme}`]: {backgroundColor: theme === 'dark' ? '#000' : '#fff',color: theme === 'dark' ? '#fff' : '#000'}};
}
const actionTypes = {[`FETCH_USER_${status}`]: `FETCH_USER_${status}`,[`UPDATE_USER_${status}`]: `UPDATE_USER_${status}`
};
const i18n = {[`greeting_${language}`]: '你好',[`farewell_${language}`]: '再见'
};
3. 扩展运算符 (…)
3.1 对象展开
const base = { a: 1, b: 2 };
const extended = { ...base, c: 3 };
console.log(extended);
const defaults = { theme: 'light', language: 'en' };
const userPreferences = { theme: 'dark' };
const finalPreferences = { ...defaults, ...userPreferences };
console.log(finalPreferences);
3.2 实际应用场景
function Button({ children, ...props }) {return (<button {...props}>{children}</button>);
}
const baseConfig = {api: 'https://api.example.com',timeout: 5000
};const devConfig = {...baseConfig,api: 'http://localhost:3000'
};
setState(prevState => ({...prevState,loading: false,data: newData
}));
4. Object.assign()
4.1 基本用法
const target = { a: 1 };
const source1 = { b: 2 };
const source2 = { c: 3 };const result = Object.assign(target, source1, source2);
console.log(result);
console.log(target);
4.2 实际应用场景
const original = { a: 1, b: { c: 2 } };
const copy = Object.assign({}, original);
function createConfig(options) {const defaults = {debug: false,timeout: 5000,retries: 3};return Object.assign({}, defaults, options);
}
const state = { user: { name: 'John' }, theme: 'light' };
const newState = Object.assign({}, state, { theme: 'dark' });
5. Object.is()
5.1 基本用法
console.log(Object.is(5, 5));
console.log(Object.is(5, '5'));
console.log(Object.is(NaN, NaN));
console.log(Object.is(+0, -0));
console.log(NaN === NaN);
console.log(Object.is(NaN, NaN)); console.log(+0 === -0);
console.log(Object.is(+0, -0));
5.2 实际应用场景
function areSameValues(x, y) {return Object.is(x, y);
}
function isReallyNaN(x) {return Object.is(x, NaN);
}
function shouldComponentUpdate(nextProps) {return !Object.is(this.props.value, nextProps.value);
}
6. 最佳实践
6.1 选择合适的方法
const merged = { ...obj1, ...obj2 };
const deepCopy = JSON.parse(JSON.stringify(obj));
if (Object.is(value1, value2)) {
}
6.2 性能考虑
const obj = {...baseObj,...middlewareObj,...finalObj
};
const result = Object.assign({}, baseConfig,environmentConfig,userConfig
);