ES6笔记-对象

依据阮一峰教程摘取的自己可能用到的特性

属性的简洁表示法

function f(x, y) {
  return {x, y};
}

// 等同于

function f(x, y) {
  return {x: x, y: y};
}

f(1, 2) // Object {x: 1, y: 2}

方法简写

const o = {
  method() {
    return "Hello!";
  }
};

// 等同于

const o = {
  method: function() {
    return "Hello!";
  }
};

Object.assign()
     
   可枚举对象的合并
        同名属性的合并
        浅拷贝

const target = { a: 1, b: 1 };

const source1 = { b: 2, c: 2 };
const source2 = { c: 3 };

Object.assign(target, source1, source2);
target // {a:1, b:2, c:3}
        用途:

                为对象添加属性

class Point {
  constructor(x, y) {
    Object.assign(this, {x, y});
  }
}

                为对象添加方法

Object.assign(SomeClass.prototype, {
  someMethod(arg1, arg2) {
    ···
  },
  anotherMethod() {
    ···
  }
});

// 等同于下面的写法
SomeClass.prototype.someMethod = function (arg1, arg2) {
  ···
};
SomeClass.prototype.anotherMethod = function () {
  ···
};

                克隆对象

function clone(origin) {
  return Object.assign({}, origin);
}

                合并多个对象

const merge =
  (...sources) => Object.assign({}, ...sources);

                为属性指定默认值

const DEFAULTS = {
  logLevel: 0,
  outputFormat: 'html'
};

function processContent(options) {
  options = Object.assign({}, DEFAULTS, options);
  console.log(options);
  // ...
}

Object.keys(),Object.values(),Object.entries()

var obj = { foo: 'bar', baz: 42 };
Object.keys(obj)
// ["foo", "baz"]
const obj = { 100: 'a', 2: 'b', 7: 'c' };
Object.values(obj)
// ["b", "c", "a"]
const obj = { foo: 'bar', baz: 42 };
Object.entries(obj)
// [ ["foo", "bar"], ["baz", 42] ]

对象的扩展运算符
        等同于Object.assign()

let aClone = { ...a };
// 等同于
let aClone = Object.assign({}, a);
let ab = { ...a, ...b };
// 等同于
let ab = Object.assign({}, a, b);

        修改现有对象部分属性

let newVersion = {
  ...previousVersion,
  name: 'New Name' // Override the name property
};









  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值