Open qiuhongbingo opened 4 years ago
/** * 装饰者模式就是在不改变原对象的基础上,对其对象进行包装和拓展,使原对象能够应对更加复杂的需求 * 这就有一点像高阶函数,因此在前端开发中非常多见 */ import React, { Component } from 'react' import { connect } from 'react-redux' class App extends Component {} export default connect(mapStateToProps, actionCreators)(App) // 或者 class CustomizedForm extends React.Component {} CustomizedForm = Form.create({})(CustomizedForm) /** * 借助装饰者模式,很容易衍生出 AOP 面向切面编程的概念 * 典型场景就是对表单的验证,我们将把表单输入逻辑校验的 validata 函数融入到 before 逻辑当中 */ Function.prototype.before = function(beforefn) { const self = this return function() { if (beforefn.apply(this, arguments) === false) return return self.apply(this, arguments) } } const validate = function() { // 表单验证逻辑 } const formSubmit = function() { // 表达提交逻辑 ajax('http:// xxx.com/login', param) } submitBtn.onclick = function() { formSubmit.before(validate) }