zoukankan      html  css  js  c++  java
  • 编码规范: 不要在类构造器内实例化当前对象

    不要在类构造器内实例化当前对象也就是说不要将类class当做function使用

    请抛弃旧有的编码习惯:

    function Element (tagName, props, children) {
      if (!(this instanceof Element)) {
        if (!_.isArray(children) && children != null) {
          children = _.slice(arguments, 2).filter(_.truthy)
        }
        return new Element(tagName, props, children)
      }
       //  ......
    }
    

    我们在TSES6编码时会习惯性沿用ES5时代的编码习惯

    export class Element implements IVNode {
      // ....
      constructor(_tagName: string);
      constructor(_tagName: string, children: any);
      constructor(_tagName: string, props: T_OBJ);
      constructor(_tagName: string, props: T_OBJ, children: T_ArrayNode);
      constructor(_tagName: string, props?: T_OBJ, children?: T_ArrayNode) {
        if (!(this instanceof Element)) {
          if (typeof props !== "undefined") {
            if (Array.isArray(children)) {
              return new Element(_tagName, props, children);
            } else {
              return new Element(_tagName, props);
            }
          } else {
            if (Array.isArray(children)) {
              return new Element(_tagName, children);
            }
          }
          return new Element(_tagName);
        }
    
      // ....
    

    这种编码方式导致class , function定义不明确,职责不清晰,我们是不提倡的

    推荐将实例化的代码抽离

    export class Element implements IVNode {
        constructor(_tagName: string, props?: T_OBJ, children?: T_ArrayNode) {
            // ...
        }
    }
    
    export default function (_tagName: string): IVNode
    export default function (_tagName: string, children: T_ArrayNode): IVNode
    export default function (_tagName: string, props: T_OBJ): IVNode
    export default function (_tagName: string, props: T_OBJ, children: T_ArrayNode): IVNode
    export default function (_tagName: string, props?: T_OBJ, children?: T_ArrayNode): IVNode {
      if (arguments.length === 2) {
        const tmp = arguments[1]
        if (Array.isArray(tmp)) {
          return new Element(_tagName, {}, tmp)
        } else {
          return new Element(_tagName, tmp, [])
        }
      } else if (arguments.length === 1) {
        return new Element(_tagName, {}, [])
      }
      return new Element(_tagName, props, children)
    }
    

    By小云菜:http://www.cnblogs.com/phillyx/

    github:http://github.com/phillyx

    版权所有,转载请注明出处

  • 相关阅读:
    Qt 学习 之 二进制文件读写
    QT学习 之 文本文件读写
    Qt学习 之 文件
    QT学习 之 三维饼图绘制
    Haskell 笔记(四)函数系统
    QT学习 之 事件与事件过滤器(分为五个层次)
    Qt学习 之 数据库(支持10种数据库)
    Qt5制作鼠标悬停显示Hint的ToolTip
    【码云周刊第 32 期】程序员眼中的 Vue 与 Angular !
    Qt学习 之 多线程程序设计(QT通过三种形式提供了对线程的支持)
  • 原文地址:https://www.cnblogs.com/phillyx/p/14487537.html
Copyright © 2011-2022 走看看