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

JavaScript Object.assign 以及 spread operator #3

Open
afishhhhh opened this issue Dec 5, 2018 · 0 comments
Open

JavaScript Object.assign 以及 spread operator #3

afishhhhh opened this issue Dec 5, 2018 · 0 comments

Comments

@afishhhhh
Copy link
Owner

Object.assign 以及 spread operator 相同点

  1. 都会将存储属性转换为数据属性
  2. 如果是一个存储属性,都会通过 get 方法读取存储属性的值,然后写入到目标对象

Object.assign 以及 spread operator 不同点

  1. 如果是一个存储属性,spread operator 直接在目标对象定义一个新的属性, Object.assign 通过 set 方法往目标对象写入属性(Demo 1, Demo 2)
  2. Object.assign 无法往目标对象写入只读属性,但是 spread operator 可以

Demo 1

Object.defineProperty(Object.prototype, 'foo', {
  set (value) {
    console.log('SET', value);
  },
});
const obj = { foo: 123 }; // obj 自身有一个 foo 属性
const clone = Object.assign({}, obj) // Object.assign 将 obj.foo 写入到 {} 的时候调用了 set

Demo 2

const o = {
  set foo (value) {
    console.log('SET', value)
  }
}
const clone2 = Object.assign(o, { foo: 123 })

Demo 3

Object.defineProperty(Object.prototype, 'bar', {
  writable: false,
  value: 'abc',
});
Object.assign({}, { bar: '123' }) // 类似 const o = {}; o.bar = '123'
const o = { bar: '123' }
{ ...o } // 

Question: Object.assign 在目标对象上写入属性,spread operator 在目标对象上定义属性 (Object init, __proto__)

ES2018: Rest/Spread Properties

@afishhhhh afishhhhh changed the title JavaScript rest operator 以及 spread operator JavaScript Object.assign 以及 spread operator Dec 6, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant