ES6学习笔记10--对象新增的方法

对象的新增方法(了解一下)


  •  Object.is() 用来比较两个值是否严格相等,与 严格比较运算符 (===)基本一致。

严格比较运算符(===)在判断 NaN 时,NaN 不等于 自身,Object.is() 可以解决此问题 

严格比运算符 (===) 在 +0 === -0 时为true,Object.is()则认为 +0与 -0 不相等

Object.is(NaN,NaN) //true
NaN === NaN // false

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

//补充扩展 ES5可通过下面代码部署Object.is
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() 方法用于对象的合并,将源对象(source) 的所有可枚举属性复制到目标对象(target)

注意:

  • 如果目标对象与源对象有同名属性,或多个源对象有同名属性,则后面的属性会覆盖前面的属性。
const target = { a: 1, b: 1 };
const source1 = { b: 2, c: 2 };
Object.assign(target, source1); // { a: 1, b: 2, c: 2}

const target = { a: { b: 'c', d: 'e' } }
const source = { a: { b: 'hello' } }
Object.assign(target, source) // { a: { b: 'hello' } }
  • 如果非对象参数出现在源对象的位置(即非首参数),会首先转成对象,如果无法转成参数,就会跳过。对于数值、布尔值类型的类型参数出现在源对象位置,是不会拷贝到目标对象上的。字符串类型参数会以数组形式拷贝入目标对象。
  • 但若非对象参数出现在目标对象的位置(即首参数),会首先转成对象,若无法转成参数,则会报错。
/*若首参数无法转换为对象,则报错**/
Object.assign(undefined) // 报错
Object.assign(null) // 报错
/*若非首参数的对象无法转化为对象,则跳过*/
let obj = {a: 1};
Object.assign(obj, undefined) // {a:1}
/**对于字符串,会以数组形式拷贝到目标对象中,数值,布尔值类型参数不会拷贝到目标对象中*/
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" }
  • Object.assign 只拷贝对象的自身属性,不拷贝继承属性,也不拷贝不可枚举的属性。
  • Object.assign() 方法实行的是浅拷贝,而不是深拷贝。如果源对象某个属性的值是对象,那么目标对象拷贝得到的是这个对象的引用。

/*若源对象的某个属性的值是复杂类型的值(对象、数组、函数),
那么使用 Object.assign拷贝依然是浅拷贝。
若要深拷贝,可以使用JSON.stringify()方法进行深拷贝。
*/
const obj1 = {a: {b: 1}};
const obj2 = Object.assign({}, obj1);
obj1.a.b = 2;
obj2.a.b // 2

/**深拷贝*/
let obj = {a: {b: 1}};
const obj1 = JSON.stringify(obj);
const obj2 = JSON.parse(obj1);
obj1.a.b = 9
obj2 // {a: {b: 1}}
  • Object.assign() 只能进行值的复制,如果要复制的值是一个取值函数,那么将求值后再复制。
  • Object.assign() 可以用来处理数组,但会把数组视为对象
/**对于数组类型的参数,object.assign会将数组视为对象,数组的索引作为键名,值作为键值**/
Object.assign([1,2,3],[4,5])  //[4,5,3]
/*Object.assign 只进行值的复制,若复制的值是一个取值函数,那么会进行求值后再复制**/
const source = {
  get foo() { return 1 }
};
const target = {};
Object.assign(target, source)
// { foo: 1 }

常见用途:为对象添加属性、方法。以及克隆/合并对象

/*为对象添加属性**/
class Point{
    constructor(x,y){
        Object.assign(this,{x,y});
    }
}
let point = new Point('x','y')
point // {x: "x", y: "y"} 通过Object.assign方法将 x 和 y 属性添加到Point类的对象实例。

/*为对象添加方法*/
Object.assign(Point.prototype,{
    movePoint(x,y){
        this.x = this.x + x;
        this.y = this.y +y;
        console.log(this.x,this.y)
    },
    deletePoint(){
        return true;
    }

})
let point = new Point('x','y')
point.movePoint('5','6'); // "x5" "y6"

/**克隆、合并对象**/
Object.assign({}, origin);
Object.assign(target, ...sources);
/*需注意的是克隆对象只能克隆对象自身的值,不能克隆继承的值,若要保持继承链,可以采用下面的代码**/
function clone(origin) {
  let originProto = Object.getPrototypeOf(origin);
  return Object.assign(Object.create(originProto), origin);
}

  • Object.getOwnPropertyDescriptors() 返回 指定对象所有自身属性(非继承属性)的描述对象

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.getOwnPropertyDescriptors() 配合 Object.defineProperties() 可以解决 Object.assign 无法正确拷贝 get 和 set 属性问题
const source = {
    set foo(value){
        console.log(value);
    },
    get foo(){
        return 1
    }
};

const target = {};
Object.defineProperties(target,Object.getOwnPropertyDescriptors(source));
Object.getOwnPropertyDescriptor(target,'foo');

// { get: get foo(){
//      return 1
//  },
//  set: set foo(){
//      console.log(value);
//  },
//  enumerable: true,
//  configurable: true }

=====>等价于
const shallowMerge = (target, source) => Object.defineProperties(
  target,
  Object.getOwnPropertyDescriptors(source)
);
  • Object.getOwnPropertyDescriptors() 配合 Object.create() 将对象属性克隆到一个新对象。属于浅拷贝
const clone = Object.create(Object.getPrototypeOf(obj),
  Object.getOwnPropertyDescriptors(obj));
  • Object.getOwnPropertyDescriptors() 实现一个对象继承另一个对象
  • Object.getOwnPropertyDescriptors() 实现 Mixin(混入)模式
/*实现继承的另一种写法**/
const prot = {
  bar:'bar'
};
const obj = Object.create(
  prot,
  Object.getOwnPropertyDescriptors({
    foo: 123,
  })
);
/*实现Mixin(混入)模式**/
let mix = (object) => ({
  with: (...mixins) => mixins.reduce(
    (c, mixin) => Object.create(
      c, Object.getOwnPropertyDescriptors(mixin)
    ), object)
});
// multiple mixins example
let a = {a: 'a'};
let b = {b: 'b'};
let c = {c: 'c'};
let d = mix(c).with(a, b);
d //{a:'a',b:'b',c:'c'}

  • Object.setPrototypeOf() / Object.getPrototypeOf()

Object.setPrototypeOf() 方法的作用于 __proto__相同,用来设置一个对象的原型对象(prototype),返回参数对象本身。

Object.getPrototypeOf() 用于读取一个对象的原型对象。

建议使用此方法设置原型对象。

Object.setPrototypeOf(object, prototype)

Object.getPrototypeOf(obj);


  • Object.keys(),Object.values(),Object.entries() 配合 for...of 循环使用

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

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

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


  • Object.fromEntries()

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

  • 将Map解构转为对象
  • 配合 URLSearchParams 将查询字符串转为对象。
// 例一
const entries = new Map([
  ['foo', 'bar'],
  ['baz', 42]
]);
Object.fromEntries(entries)
// { foo: "bar", baz: 42 }
// 例二
const map = new Map().set('foo', true).set('bar', false);
Object.fromEntries(map)
// { foo: true, bar: false }

/*配合URLSearchParams对象,将查询字符串转为对象。**/
Object.fromEntries(new URLSearchParams('foo=bar&baz=qux'))
// { foo: "bar", baz: "qux" }

 

 

 

 

 

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值