简介

Mixin 本质就是一组方法。
Mixin 的目的是横向抽离出组件的相似代码。
相似概念:面向切面编程、插件。

  1. // 将 mixins 上的方法,绑定到 obj.__proto__ 上,使得 obj 可以使用 mixins 的方法
  2. const createMixin = (obj, mixins) => {
  3. obj.__proto__ = Object.assign(obj.__proto__, mixins);
  4. return obj;
  5. }
  6. // 使用示例
  7. // mixins
  8. const sayMixin = {
  9. say: function () {
  10. console.log('hello, my name is ' + this.name);
  11. }
  12. }
  13. class User {
  14. constructor(name) {
  15. this.name = name;
  16. }
  17. }
  18. const user = new User('konsoue');
  19. createMixin(user, sayMixin);
  20. user.say()

我们使用继承时,是纵向的父子关系,需要去额外抽象类出来,处理这些逻辑。
而 mixin 可以让我们横向的,像在横的方向切一刀似的,假如一些方法、逻辑。

React 中的 mixin

  1. var SetIntervalMixin = {
  2. componentWillMount: function () {
  3. this.intervals = []
  4. },
  5. setInterval: function (fn, timeout, ...args) {
  6. this.intervals.push(setInterval(fn, timeout, ...args))
  7. },
  8. componentWillUnmount: function () {
  9. this.intervals.forEach(clearInterval)
  10. }
  11. }
  12. var TickTock = React.creatClass({
  13. mixins: [SetIntervalMixin],
  14. getInitialState: function () {
  15. return { seconds: 0 }
  16. }
  17. })