Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
ckinmind opened this issue Jan 20, 2017 · 0 comments

Comments

Projects
None yet
1 participant
@ckinmind
Copy link
Owner

commented Jan 20, 2017

做了一个测试

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官网在线测试地址

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.