十八、对象方法扩展

郁子小于 1 分钟约 242 字笔记ECMAScript尚硅谷李强

(一)Object.is

  • 判断两个值是否完全相等
    • === 基本相同
    • 但是判断 NaN 时不同
  • NaN 与任何数作比较
    • 在判断不相等时为 true
    • 其他情况都是 false
console.log(Object.is(120, 121), 120 === 121);
// false false

console.log(Object.is(120, 120), 120 === 120);
// true true

console.log(Object.is(NaN, NaN), NaN === NaN);
// true false

(二)Object.assign

  • 对象的合并
const config1 = {
  host: "localhost",
  port: 3306,
  name: "root",
  pass: "root",
  test: "test",
};
const config2 = {
  host: "http://www.baidu.com",
  port: 33060,
  name: "baidu.com",
  pass: "baidu",
  test2: "test2",
};
console.log(Object.assign(config1, config2));
// {host: 'http://www.baidu.com', port: 33060, name: 'baidu.com', pass: 'baidu', test: 'test', …}
// host: "http://www.baidu.com"
// name: "baidu.com"
// pass: "baidu"
// port: 33060
// test: "test"
// test2: "test2"

(三)Object.setPrototypeOf && Object.getPrototypeOf

  • 设置/获取原型对象
  • 不建议这样设置
    • 应该在 Object.create 创建对象时就把原型对象给设置好
const school = {
  name: "尚硅谷",
};
const cities = {
  xiaoqu: ["北京", "上海", "深圳"],
};
Object.setPrototypeOf(school, cities);
console.log(school);
// {name: '尚硅谷'}

console.log(Object.getPrototypeOf(school));
// {xiaoqu: Array(3)}
上次编辑于: