ts-15 Mixins混入

53 阅读1分钟

什么是混入Mixins

  • 简单来说可以看做为 合并

对象混入

  • 可以使用es6的Object.assign用来合并多个对象
  •   interface Name {
        name: string
      }
      interface Age {
        age: number
      }
      interface Sex {
        sex: string
      }
    
      let obj1: Name = { name: '瑞雯' }
      let obj2: Age = { age: 12 }
      let obj3: Sex = { sex: '女' }
    
      let newObj = Object.assign(obj1, obj2, obj3)
      console.log(newObj) // { name: '瑞雯', age: 12, sex: '女' }
    

类混入

  • 首先声明三个 mixins 类
    •   class Name {
          name: string
          getName(): string {
            return this.name
          }
        }
        class Age {
          age: number
        }
      
        class IsMan {
          IsMan: boolean
          changeIsMan() {
            this.IsMan = !this.IsMan
          }
        }
      
  • 在创建一类用来结合上面创建的mixins类
    • 没有使用 extends 去继承,而是用 implements 把类当做成了接口
    •   class Persons implements Name, Age, IsMan {
          name: string = '瑞雯'
          age: number = 12
          IsMan: boolean = false
          getName: () => string
          changeIsMan: () => string
        }
      
  • 定义和函数用来做混入
    • 参数
      • fucntion mixins(目标对象,要混入的对象)
    • 使用 Object.getOwnPropertyNames 去获取 i 上的prototype
    •   function mixins(cur: any, item: any[]) {
          item.forEach(i => {
            // console.log(i) // [Function: Name] [Function: Age] [Function: IsMan]
      
            // 使用 Object.getOwnPropertyNames 去获取 i 上的prototype
            Object.getOwnPropertyNames(i.prototype).forEach(name => {
              // console.log(name) // 打印出 constructor 和  定义的方法
              cur.prototype[name] = i.prototype[name]
            })
          })
        }
        
        mixins(Persons, [Name, Age, IsMan])
        
        let p = new Persons()
        console.log(p.IsMan) // false
        p.changeIsMan()
        console.log(p.IsMan) // true