介绍

  • new 操作单独封装
  • 遇到new 使用工厂模式

UML类图

点击查看【processon】

代码

  1. class Product {
  2. name
  3. constructor(name) {
  4. this.name = name
  5. }
  6. init() { console.log('init') }
  7. fn1() {}
  8. fn2() {}
  9. }
  10. class Creator {
  11. create(name) {
  12. return new Product(name)
  13. }
  14. }
  15. const creator = new Creator()
  16. const p = creator.create('p1')
  17. console.log(p.init())

场景

  • jquery
  • React.createElement
  • Vue的异步组件
    • Vue.component
    • defineAsyncComponent ``javascript // vue2 Vue.component('async-example', function (resolve, reject) { setTimeout(function () { // 向resolve` 回调传递组件定义 resolve({ template: ‘
      I am async!
      ‘ }) }, 1000) })

// vue3 const AsyncComp = defineAsyncComponent( () => new Promise((resolve, reject) => { resolve({ template: ‘

I am async!
‘ }) }) ) ```