mixin混入逻辑

有A对象和B对象,A, B对象有有方法属性和数据属性。现在有一个需求,将A没有而B有的属性混入到A中。A有而且B也有的属性不混入以A为准。通过这种混入机制(滚雪球的方式)可以不断地扩充一个对象地的功能。暂且将它定义为混入模式。这种模式在Vue构建的过程中使用到,在Express构建的过程中也使用到。混入模式是JS构建复杂对象的一种常用的模式。

function mixin(dest, src, cover) {
  if (dest === undefined) {
    throw Error("dest can not null");
  }
  if (src === undefined) {
    throw Error("src can not null");
  }
  if (cover === undefined) {
    cover = false;
  }
  Object.getOwnPropertyNames(src).forEach(function(prop) {
    if (Object.prototype.hasOwnProperty.call(dest, prop)) {
      return;
    }
    let value = Object.getOwnPropertyDescriptor(src, prop);
    Object.defineProperty(dest, prop, value);
  });
}

const a = {
  x: 1,
  y: 2,
  z: 3,
  say: function() {
    console.log("local state (x, y, z)");
  }
}

const b = {
  r: 4,
  s: 5,
  z: 6,
  run: function() {
    console.log("local state (r, s, z)");
  }
}

const c = {
  m: 4,
  n: 5,
  y: 6,
  bit: function() {
    console.log("local state (m, n, y)");
  }
}

mixin(a, b);
mixin(a, c);

console.log("mixin a ", a);
    原文作者:洛神赋
    原文地址: https://segmentfault.com/a/1190000020013292
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞