属性的简洁表示法

ES6 允许直接写入变量和函数作为对象的属性和方法,让书写更加简洁

1
2
3
4
5
6
const foo = 'bar'
const baz = { foo }
baz // {foo: "bar"}

// 等同于
const baz = { foo: foo }

上面代码中,变量foo直接写在大括号里面。这时,属性名就是变量名, 属性值就是变量值。除了属性简写,方法也可以简写。

1
2
3
4
5
6
7
8
9
10
11
12
13
const o = {
method() {
return 'Hello!'
},
}

// 等同于

const o = {
method: function () {
return 'Hello!'
},
}

这种写法用于函数的返回值,将会非常方便。

1
2
3
4
5
6
7
8
function getPoint() {
const x = 1
const y = 10
return { x, y }
}

getPoint()
// {x:1, y:10}

CommonJS 模块输出一组变量,就非常合适使用简洁写法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
let ms = {}

function getItem(key) {
return key in ms ? ms[key] : null
}

function setItem(key, value) {
ms[key] = value
}

function clear() {
ms = {}
}

module.exports = { getItem, setItem, clear }
// 等同于
module.exports = {
getItem: getItem,
setItem: setItem,
clear: clear,
}

注意,简写的对象方法不能用作构造函数,会报错。

1
2
3
4
5
6
7
const obj = {
f() {
this.foo = 'bar'
},
}

new obj.f() // 报错

属性名表达式

JavaScript 定义对象的属性,有两种方法。

1
2
3
4
5
// 方法一
obj.foo = true

// 方法二
obj['a' + 'bc'] = 123

上面代码的方法一是直接用标识符作为属性名,方法二是用表达式作为属性名,这时要将表达式放在方括号之内。

但是,如果使用字面量方式定义对象(使用大括号),在 ES5 中只能使用方法一(标识符)定义属性。

1
2
3
4
var obj = {
foo: true,
abc: 123,
}

ES6 允许字面量定义对象时,用方法二(表达式)作为对象的属性名,即把表达式放在方括号内。

1
2
3
4
5
6
let propKey = 'foo'

let obj = {
[propKey]: true,
['a' + 'bc']: 123,
}

表达式还可以用于定义方法名

1
2
3
4
5
6
7
let obj = {
['h' + 'ello']() {
return 'hi'
},
}

obj.hello() // hi

注意,属性名表达式与简洁表示法,不能同时使用,会报错。

1
2
3
4
5
6
7
8
// 报错
const foo = 'bar';
const bar = 'abc';
const baz = { [foo] };

// 正确
const foo = 'bar';
const baz = { [foo]: 'abc'};

注意,属性名表达式如果是一个对象,默认情况下会自动将对象转为字符串[object Object],这一点要特别小心。

1
2
3
4
5
6
7
8
9
const keyA = { a: 1 }
const keyB = { b: 2 }

const myObject = {
[keyA]: 'valueA',
[keyB]: 'valueB',
}

myObject // Object {[object Object]: "valueB"}

上面代码中,[keyA][keyB]得到的都是[object Object],所以[keyB]会把[keyA]覆盖掉,而myObject最后只有一个[object Object]属性。

方法的 name 属性

函数的name属性,返回函数名。对象方法也是函数,因此也有name属性。

1
2
3
4
5
6
7
const person = {
sayName() {
console.log('hello!')
},
}

person.sayName.name // "sayName"

上面代码中,方法的name属性返回函数名(即方法名)。

如果对象的方法使用了取值函数(getter)和存值函数(setter),则name属性不是在该方法上面,而是该方法的属性的描述对象的getset属性上面,返回值是方法名前加上getset

1
2
3
4
5
6
7
8
9
10
11
12
const obj = {
get foo() {},
set foo(x) {},
}

obj.foo.name
// TypeError: Cannot read property 'name' of undefined

const descriptor = Object.getOwnPropertyDescriptor(obj, 'foo')

descriptor.get.name // "get foo"
descriptor.set.name // "set foo"

有两种特殊情况:bind方法创造的函数,name属性返回bound加上原函数的名字;Function构造函数创造的函数,name属性返回anonymous

1
2
3
4
5
6
new Function().name // "anonymous"

var doSomething = function () {
// ...
}
doSomething.bind().name // "bound doSomething"

如果对象的方法是一个 Symbol 值,那么name属性返回的是这个 Symbol 值的描述。

1
2
3
4
5
6
7
8
const key1 = Symbol('description')
const key2 = Symbol()
let obj = {
[key1]() {},
[key2]() {},
}
obj[key1].name // "[description]"
obj[key2].name // ""

上面代码中,key1对应的 Symbol 值有描述,key2没有。

对象的可枚举性和遍历

1
2
3
4
5
6
7
let obj = { a: 1 }

Object.getOwnPropertyDescriptor(obj, 'a')
// configurable: true
// enumerable: true
// value: 1
// writable: true

enumerable属性成为可枚举性,如果该属性为 false,有一些操作会省略当前属性。

有四个操作会忽略 enumerable 为 false 的属性。

  • for...in循环:只遍历对象自身继承 的可枚举属性。
  • Object.keys():返回对象自身的所有可枚举的属性的键名
  • JSON.stringify() :只串行化对象自身的可枚举属性。
  • Object.assign():忽略enumerable 为 false 的属性,只拷贝对象自身 的可枚举的属性。

属性的遍历

  • for...in 遍历对象自身 继承 的可枚举属性。(不包括 Symbol 属性)
  • Object.keys() 返回一个数组,包括对象自身 的(不包括继承的)所有可枚举属性的键名。(不包括 Symbol 属性)
  • Object.getOwnPropertyNames(obj) , 返回一个数组,包含对象自身的所有属性的键名。(不包括 Symbol 属性,但是包含不可枚举的属性)
  • Object.getOwnPropertySymbols(obj),返回一个数组,包含对象自身的所有 Symbol 属性的键名。
  • Reflect.ownKeys(obj),返回一个数组,包括对象自身的所有键名。(不管键名是否为 Symbol 值,不管是否可枚举)。

Object 的方法扩展

Object() 方法可以把参数变成对象

1
2
Object(1)   // Number
Object(true) // Boolean

Object.is()

它用来比较两个值是否严格相等,与严格比较运算符(===)的行为基本一致。

1
2
3
4
Object.is('foo', 'foo')
// true
Object.is({}, {})
// false

不同之处只有两个:一是+0不等于-0,二是NaN等于自身。

1
2
3
4
5
;+0 === -0 //true
NaN === NaN // false

Object.is(+0, -0) // false
Object.is(NaN, NaN) // true

ES5 可以通过下面的代码,部署Object.is

1
2
3
4
5
6
7
8
9
10
11
12
13
Object.defineProperty(Object, 'is', {
value: function (x, y) {
if (x === y) {
// 针对+0 不等于 -0的情况
return x !== 0 || 1 / x === 1 / y
}
// 针对NaN的情况
return x !== x && y !== y
},
configurable: true,
enumerable: false,
writable: true,
})

Object.assign()

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

1
2
3
4
5
6
7
const target = { a: 1 }

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

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

Object.assign方法的第一个参数是目标对象,后面的参数都是源对象。

注意,如果目标对象与源对象有同名属性,或多个源对象有同名属性,则后面的属性会覆盖前面的属性

1
2
3
4
5
6
7
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}

如果只有一个参数,Object.assign会直接返回该参数。

1
2
const obj = { a: 1 }
Object.assign(obj) === obj // true

如果该参数不是对象,则会先转成对象,然后返回。

1
typeof Object.assign(2) // "object"

由于undefinednull无法转成对象,所以如果它们作为参数,就会报错

1
2
Object.assign(undefined) // 报错
Object.assign(null) // 报错

但是,如果undefinednull不在首参数,就不会报错。

1
2
3
let obj = { a: 1 }
Object.assign(obj, undefined) === obj // true
Object.assign(obj, null) === obj // true

除了字符串会以数组形式,拷贝入目标对象,其他值都不会产生效果:

1
2
3
4
5
6
const v1 = 'abc'
const v2 = true
const v3 = 10

const obj = Object.assign({}, v1, v2, v3)
console.log(obj) // { "0": "a", "1": "b", "2": "c" }

上述代码中数值和布尔值都会被忽略。这是因为只有字符串的包装对象,会产生可枚举属性。

1
2
3
Object(true) // {[[PrimitiveValue]]: true}
Object(10) // {[[PrimitiveValue]]: 10}
Object('abc') // {0: "a", 1: "b", 2: "c", length: 3, [[PrimitiveValue]]: "abc"}

上面代码中,布尔值、数值、字符串分别转成对应的包装对象,可以看到它们的原始值都在包装对象的内部属性[[PrimitiveValue]]上面,这个属性是不会被Object.assign拷贝的。只有字符串的包装对象,会产生可枚举的实义属性,那些属性则会被拷贝。

Object.assign拷贝的属性是有限制的,只拷贝源对象的自身属性(不拷贝继承属性),也不拷贝不可枚举的属性(enumerable: false)。

1
2
3
4
5
6
7
Object.assign({b: 'c'},
Object.defineProperty({}, 'invisible', {
enumerable: false,
value: 'hello'
})
)
// { b: 'c' }

上述需要拷贝的对象只有一个不可枚举属性 invisible,所以这个属性并没有被拷贝进去。

属性名为 Symbol 值的属性,也会被拷贝:

1
2
Object.assign({ a: 'b' }, { [Symbol('c')]: 'd' })
// { a: 'b', Symbol(c): 'd' }

注意点

浅拷贝

如果源对象某个属性的值是对象,那么目标对象拷贝得到的是这个对象的引用。

1
2
3
4
5
const obj1 = {a: {b: 1}};
const obj2 = Object.assign({}, obj1);

obj1.a.b = 2;
obj2.a.b // 2

同名属性的替换

1
2
3
4
const target = { a: { b: 'c', d: 'e' } }
const source = { a: { b: 'hello' } }
Object.assign(target, source)
// { a: { b: 'hello' } }

上述代码中,a被整个替换,不会得到{ a: { b: 'hello', d: 'e' } }这样的结果。

数组的处理

可以用来处理数组,但是会把数组视为对象。

1
2
Object.assign([1, 2, 3], [4, 5])
// [4, 5, 3]

上述代码中,以后一个数组的值替换了目标数组中对应下标的值。

取值函数的处理

Object.assign只能进行值的复制,如果要复制的值是一个取值函数,那么将求值后再复制:

1
2
3
4
5
6
7
8
9
const source = {
get foo() {
return 1
},
}
const target = {}

Object.assign(target, source)
// { foo: 1 }

上面代码中,source对象的foo属性是一个取值函数,Object.assign不会复制这个取值函数,只会拿到值以后,将这个值复制过去。

常见用途

为对象添加属性

1
2
3
4
5
class Point {
constructor(x, y) {
Object.assign(this, { x, y })
}
}

为对象添加方法

1
2
3
4
5
6
7
8
Object.assign(SomeClass.prototype, {
someMethod(arg1, arg2) {
···
},
anotherMethod() {
···
}
});

克隆对象

1
2
3
function clone(origin) {
return Object.assign({}, origin)
}

合并多个对象

1
const merge = (target, ...sources) => Object.assign(target, ...sources)

为属性指定默认值

1
2
3
4
5
6
7
8
9
10
const DEFAULTS = {
logLevel: 0,
outputFormat: 'html',
}

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

上面代码中,DEFAULTS对象是默认值,options对象是用户提供的参数。Object.assign方法将DEFAULTSoptions合并成一个新对象,如果两者有同名属性,则options的属性值会覆盖DEFAULTS的属性值。

Object.getOwnPropertyDescriptors()

ES5 的Object.getOwnPropertyDescriptor()获取一个对象中某个属性的描述

1
2
Object.getOwnPropertyDescriptor('123', length)
// {value: 3, writable: false, enumrable: false, configurable:false}

ES2017 引入了Object.getOwnPropertyDescriptors()方法,返回指定对象所有自身属性(非继承属性)的描述对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const obj = {
foo: 123,
get bar() {
return 'abc'
},
}

Object.getOwnPropertyDescriptors(obj)
// { foo:
// { value: 123,
// writable: true,
// enumerable: true,
// configurable: true },
// bar:
// { get: [Function: get bar],
// set: undefined,
// enumerable: true,
// configurable: true } }

OBject.keys()

ES5 引入了Object.keys方法,返回一个数组,成员是参数对象自身的(不含继承的)所有可遍历(enumerable)属性的键名。

1
2
3
var obj = { foo: 'bar', baz: 42 }
Object.keys(obj)
// ["foo", "baz"]

Object.values()

Object.values方法返回一个数组,成员是参数对象自身的(不含继承的)所有可遍历(enumerable)属性的键值。

1
2
3
const obj = { foo: 'bar', baz: 42 }
Object.values(obj)
// ["bar", 42]

Object.entries()

Object.entries()方法返回一个数组,成员是参数对象自身的(不含继承的)所有可遍历(enumerable)属性的键值对数组。

1
2
3
const obj = { foo: 'bar', baz: 42 }
Object.entries(obj)
// [ ["foo", "bar"], ["baz", 42] ]

Object.fromEntries()

Object.fromEntries()方法是Object.entries()的逆操作,用于将一个键值对数组转为对象。

1
2
3
4
5
Object.fromEntries([
['foo', 'bar'],
['baz', 42],
])
// { foo: "bar", baz: 42 }

Object.getPrototypeOf()

Object.getPrototypeOf()用于读取一个对象的原型对象,如果参数不是对象,会被自动转为对象。

1
2
3
4
5
6
7
8
9
10
11
12
function Rectangle() {
// ...
}

const rec = new Rectangle()

Object.getPrototypeOf(rec) === Rectangle.prototype
// true

Object.setPrototypeOf(rec, Object.prototype)
Object.getPrototypeOf(rec) === Rectangle.prototype
// false

如果参数是 undefined 或 null,它们无法转为对象,所以会报错:

1
2
3
4
5
Object.getPrototypeOf(null)
// TypeError: Cannot convert undefined or null to object

Object.getPrototypeOf(undefined)
// TypeError: Cannot convert undefined or null to object

Object.setPrototypeOf()

Object.setPrototypeOf方法的作用与__proto__相同,用来设置一个对象的prototype对象,返回参数对象本身。它是 ES6 正式推荐的设置原型对象的方法,如果第一个参数不是对象,会自动转为对象。

1
2
3
4
5
// 格式
Object.setPrototypeOf(object, prototype)

// 用法
const o = Object.setPrototypeOf({}, null);

由于undefinednull无法转为对象,所以如果第一个参数是undefinednull,就会报错。

1
2
3
4
5
Object.setPrototypeOf(undefined, {})
// TypeError: Object.setPrototypeOf called on null or undefined

Object.setPrototypeOf(null, {})
// TypeError: Object.setPrototypeOf called on null or undefined

参考资料:

《ES6 标准入门》(第 3 版) 阮一峰著