npm包之merge-descriptors
前言
merge-descriptors用于继承其它对象的属性和属性描述符。
语法
mixin(dest, src, redefine);
-
a 被继承者
-
b 继承者
-
true 当继承者存在继承的属性时,是否继续继承 (默认继承 ture)
-
返回继承后的对象 b (函数执行后b对象已经被重新赋值,可以不使用返回的对象)
-
附录(文档描述)
/**
* 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) {
...
}
示例
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);
总结
- 一般搭配Object.defineProperty()设置属性的对象;
- 主要用于合并对象的描述符;
- 可以和Object.assign()方法去比较;
原博客链接:https://www.cnblogs.com/xpengp/