Bootstrap

ES6 对象扩展:对象简写,对象属性 表达式,扩展运算符 ...,Object.assign,Object.is,用法和应用场景

1. 对象属性简写

1.1 基本语法

// 传统写法
const name = 'John';
const age = 25;
const user = {
  name: name,
  age: age
};

// ES6 简写语法
const user = {
  name,
  age
};

1.2 实际应用场景

// 1. 函数返回对象
function createUser(name, age, email) {
  return {
    name,
    age,
    email
  };
}

// 2. React 组件状态
function useState(initialState) {
  const state = initialState;
  const setState = (newState) => {
    // 更新逻辑
  };
  return { state, setState };
}

// 3. 模块导出
const actions = {
  increment,
  decrement,
  reset
};
export default actions;

2. 对象属性表达式

2.1 基本语法

const prefix = 'user';
const id = 1;

// 计算属性名
const user = {
  [`${prefix}_${id}`]: 'John',
  [`${prefix}Email`]: '[email protected]'
};

console.log(user.user_1); // 'John'
console.log(user.userEmail); // '[email protected]'

2.2 实际应用场景

// 1. 动态键名对象
function createStyles(theme) {
  return {
    [`button_${theme}`]: {
      backgroundColor: theme === 'dark' ? '#000' : '#fff',
      color: theme === 'dark' ? '#fff' : '#000'
    }
  };
}

// 2. Redux action types
const actionTypes = {
  [`FETCH_USER_${status}`]: `FETCH_USER_${status}`,
  [`UPDATE_USER_${status}`]: `UPDATE_USER_${status}`
};

// 3. 国际化键值对
const i18n = {
  [`greeting_${language}`]: '你好',
  [`farewell_${language}`]: '再见'
};

3. 扩展运算符 (…)

3.1 对象展开

// 基本用法
const base = { a: 1, b: 2 };
const extended = { ...base, c: 3 };
console.log(extended); // { a: 1, b: 2, c: 3 }

// 对象合并
const defaults = { theme: 'light', language: 'en' };
const userPreferences = { theme: 'dark' };
const finalPreferences = { ...defaults, ...userPreferences };
console.log(finalPreferences); // { theme: 'dark', language: 'en' }

3.2 实际应用场景

// 1. React 组件属性传递
function Button({ children, ...props }) {
  return (
    <button {...props}>
      {children}
    </button>
  );
}

// 2. 配置合并
const baseConfig = {
  api: 'https://api.example.com',
  timeout: 5000
};

const devConfig = {
  ...baseConfig,
  api: 'http://localhost:3000'
};

// 3. 状态更新
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); // { a: 1, b: 2, c: 3 }
console.log(target); // { a: 1, b: 2, c: 3 } - 目标对象被修改

4.2 实际应用场景

// 1. 创建对象的浅拷贝
const original = { a: 1, b: { c: 2 } };
const copy = Object.assign({}, original);

// 2. 合并默认配置
function createConfig(options) {
  const defaults = {
    debug: false,
    timeout: 5000,
    retries: 3
  };
  
  return Object.assign({}, defaults, options);
}

// 3. 不可变状态更新
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)); // true
console.log(Object.is(5, '5')); // false
console.log(Object.is(NaN, NaN)); // true
console.log(Object.is(+0, -0)); // false

// 与 === 的区别
console.log(NaN === NaN); // false
console.log(Object.is(NaN, NaN)); // true

console.log(+0 === -0); // true
console.log(Object.is(+0, -0)); // false

5.2 实际应用场景

// 1. 精确的值比较
function areSameValues(x, y) {
  return Object.is(x, y);
}

// 2. NaN 检测
function isReallyNaN(x) {
  return Object.is(x, NaN);
}

// 3. React 中的值比较
function shouldComponentUpdate(nextProps) {
  return !Object.is(this.props.value, nextProps.value);
}

6. 最佳实践

6.1 选择合适的方法

// 1. 简单对象合并:使用扩展运算符
const merged = { ...obj1, ...obj2 };

// 2. 需要深拷贝:使用其他方法
const deepCopy = JSON.parse(JSON.stringify(obj));

// 3. 精确值比较:使用 Object.is()
if (Object.is(value1, value2)) {
  // 相等处理
}

6.2 性能考虑

// 1. 避免过深的对象展开
const obj = {
  ...baseObj,
  ...middlewareObj,
  ...finalObj
};

// 2. 使用 Object.assign 处理多个源对象
const result = Object.assign({}, 
  baseConfig,
  environmentConfig,
  userConfig
);
;