mixin混入逻辑

11次阅读

共计 801 个字符,预计需要花费 3 分钟才能阅读完成。

有 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);

正文完
 0