关于ES7 notation (Object Spread),即react中的Spread Attributes

@ckinmind 2017-01-20 17:38:53发表于 ckinmind/ReactCollect 重要

做了一个测试

let a = {
  test: 'just test',
  name: 'ck',
  message: 'haha'
};
let b = {...a, message:'hehe'};

console.log(b);
//打印内容
Object {
  "message": "hehe",
  "name": "ck",
  "test": "just test"
}
  1. 使用了...操作符,注意最后的message属性覆盖了a中的message值
  2. 打印出来的b中的属性是平级的
  3. 通过在babel官网测试,let b = {...a, message:'hehe'};转为ES5的代码是var b = _extends({}, a, { message: 'hehe' });, 而_extends使用Object.assign实现的
  4. 这种方式只能实现浅拷贝,无法深拷贝

完整的babel转译前后代码

let a = {
  test: 'just test',
  name: 'ck',
  message: 'haha'
};
let b = {...a,message:'hehe'};

// ES5
'use strict';

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var a = {
  test: 'just test',
  name: 'ck',
  message: 'haha'
};
var b = _extends({}, a, { message: 'hehe' });

备注:babel官网在线测试地址