6. Object扩展

2/17/2022 ES6

# 1. 对象属性方法同名简写

ES6 允许在括号里直接写入变量和函数,作为对象的属性和方法(说白了就是同名简写)

var id = 1007
var obj = {
  id,
  fn(){ ... }
}

等价于
var obj = {
  id: id,
  fn: function(){ ... }
}

简写应用场景

// net.js 配置调用接口并导出
function getUser(user) {
  //...
}

function setProfile(name, id) {
  //...
}
// 导出
export {
  getUser,
  setProfile
}
// 相当于
export {
  getUser:getUser,
  setProfile:setProfile
}

# 2. super 关键字

super指向当前对象的原型,相当于this.__proto__,且只能在对象方法中使用

var objProto = { name: 'objProto ' }
var obj = {
	name: 'obj',
	fn() {
		alert(super.name)
	},
}
Object.setPrototypeOf(obj, objProto)
obj.fn() // 'objProto'

注意:一些浏览器不能识别super关键字,需要 babel 转译

# 3. ...操作符解构属性

let a = { id: 107, name: 'jack' }
let b = { ...a } // {id: 107, name: 'jack'}

let c = { id: 33, age: 18 }
let d = { id: 55, name: 'tom' }
let e = { ...c, ...d } // {id:55,age:18,name:'tom'} 合并c和d,后边覆盖前边的同名属性

let f = { ...[1, 2, 3] } // {0: 1, 1: 2, 2: 3}

# 4. assign

用于对象合并,将源对象的所有可枚举属性复制到目标对象Object.assign(target, obj1, ... ,obj)

let target = { a: 1 }
let obj1 = { b: 1 }
let obj2 = { c: 1 }

Object.assign(target, obj1, obj2)
target // {a:1,b:1,c:1}

// 等价于
target = { ...target, ...obj1, ...obj2 }

# 5. keys

返回由可枚举属性名组成的数组Object.keys(obj)

Object.keys({ id: 1007, name: 'jack' }) // ['id','name']

let obj = {
	id: 107,
	name: 'jack',
}
Object.keys(obj).forEach((prop) => {
	alert(prop)
})

# 6. values、entries、fromEntries

下面是汇总:

Object.keys({key1:val1,...,key:val}) => [key1,...,key]
Object.values({key1:val1,...,key:val}) => [val1,...,val]
Object.entries({key1:val1,...,key:val}) => [[key1,val1],...,[key,val]]
Object.fromEntries([[key1,val1],...,[key,val]]) => {key1:val1,...,key:val}

用法:

// keys, values, entries
let { keys, values, entries } = Object // 还记得解构吗?
let obj = { a: 1, b: 2, c: 3 }

for (let key of keys(obj)) {
	console.log(key) // 'a', 'b', 'c'
}

for (let value of values(obj)) {
	console.log(value) // 1, 2, 3
}

for (let [key, value] of entries(obj)) {
	console.log([key, value]) // ['a', 1], ['b', 2], ['c', 3]
}

// fromEntries
Object.fromEntries([
	['id', 107],
	['age', 18],
])
// { id: 107, age: 18}

// 应用
const map = new Map().set('foo', true).set('bar', false)
Object.fromEntries(map)
// { foo: true, bar: false }
    人生如梦,
    我投入了的却是真情,
    世界先爱了我,
    我不能不爱它。
    红莲华
    x
    loading...