介绍
- new 操作单独封装
- 遇到new 使用工厂模式
UML类图
代码
class Product {
name
constructor(name) {
this.name = name
}
init() { console.log('init') }
fn1() {}
fn2() {}
}
class Creator {
create(name) {
return new Product(name)
}
}
const creator = new Creator()
const p = creator.create('p1')
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!
‘
})
})
)
```