前言

merge-descriptors用于继承其它对象的属性和属性描述符。

语法

mixin(dest, src, redefine);

  • a 被继承者

  • b 继承者

  • true 当继承者存在继承的属性时,是否继续继承 (默认继承 ture)

  • 返回继承后的对象 b (函数执行后b对象已经被重新赋值,可以不使用返回的对象)

  • 附录(文档描述)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    /**
    * Merge the property descriptors of `src` into `dest`
    *
    * @param {object} dest Object to add descriptors to
    * @param {object} src Object to clone descriptors from
    * @param {boolean} [redefine=true] Redefine `dest` properties with `src` properties
    * @returns {object} Reference to dest
    * @public
    */

    function merge(dest, src, redefine) {
    ...
    }

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
const mixin = require('merge-descriptors');

let a = {};
Object.defineProperty(a, 'name', {
value:1,
configurable: true,
enumerable: true,
writable: true,
});
console.log(a);

let b = {
name: 'xpengp'
};
// let c = {};
// mixin(b, a, false);

let c = mixin(b, a, false);

mixin(b, a, false);

console.log(a, b, c);

a.name = 2;
console.log(a, b, c);

b.name = 3;
console.log(a, b, c);

c.name = 4;
console.log(a, b, c);

总结

  1. 一般搭配Object.defineProperty()设置属性的对象;
  2. 主要用于合并对象的描述符;
  3. 可以和**Object.assign()**方法去比较;