19.对象方法扩展

 

对象方法扩展

(1) Object.is()

Object.is 比较两个值是否严格相等,与『===』行为基本一致

1
2
3
4
// 1. Object.is() 判断两个值是否完全相等
console.log(Object.is(120, 120)); // true
console.log(Object.is(NaN, NaN)); // true
console.log(NaN === NaN); // false

(2) Object.assign()

Object.assign(obj_source, obj_target) 对象的合并,将源对象的所有可枚举属性,复制到目标对象

Object.assign(obj_1, obj_2): 用 obj_2 去合并覆盖 obj_1,返回合并后的结果,同时 obj_1 的值会被修改,变为合并后的结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 2. Object.assign() 对象的合并
const config1 = {
ip: '192.168.100.10',
port: 3306,
password: '123456'
};
const config2 = {
username: 'root',
password: 'abcdef'
}
const mergeConfig = Object.assign(config1, config2);
console.log(mergeConfig); // {ip: '192.168.100.10', port: 3306, password: 'abcdef', username: 'root'}
console.log(config1); // {ip: '192.168.100.10', port: 3306, password: 'abcdef', username: 'root'}
console.log(config2); // {username: 'root', password: 'abcdef'}

(3) Object.setPrototypeOf() 和 Object.getPrototypeof()

  • Object.setPrototypeOf(obj_1, obj_2): 设置原型对象,设置 obj_1 的原型为 obj_2
  • Object.getPrototypeof(obj): 获取原型对象
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// 3. Object.setPrototypeOf() 和 Object.getPrototypeof()
const school = {
name: 'university'
}
const district = {
city: ['London','Paris','Boston']
}
Object.setPrototypeOf(school, district);

console.log(Object.getPrototypeOf(school));
/**
* {city: Array(3)}
* city: (3) ['London', 'Paris', 'Boston']
* [[Prototype]]: Object
*/

console.log(school);
/**
* {name: 'university'}
* name: "university"
* [[Prototype]]: Object
* city: (3) ['London', 'Paris', 'Boston']
* [[Prototype]]: Object
*/