定义
为了给一个函数赋能,增强它的某种能力,可以动态的添加对象的行为
场景
React的高阶组件HOC
用高阶组件HOC来装饰Target Component
import React from 'react'const yellowHOC = WrapperComponent => {return class extends React.Component {render() {<div style={{ backgroundColor: 'yellow' }}><WrapperComponent {...this.props} /></div>}}}export default yellowHOC
import React from 'react'import yellowHOC from './yellowHOC'// 定义一个带有装饰黄色背景的高阶组件,用它来装饰目标组件class TargetComponent extends React.Compoment {render() {return <div>66666</div>}}export default yellowHOC(TargetComponent)
能力扩展
const kuanWrite = function() {this.writeChinese = function() {console.log('我只会写中文')}}// 通过装饰器给阿宽加上写英文的能力const Decorator = function(old) {this.oldWrite = old.writeChinesethis.writeEnglish = function() {console.log('给阿宽赋予写英文的能力')}this.newWrite = function() {this.oldWrite()this.writeEnglish()}}const oldKuanWrite = new kuanWrite()const decorator = new Decorator(oldKuanWrite)decorator.newWrite()
输出
我只会写中文给阿宽赋予写英文的能力
