JavaScript学习 | 青训营笔记

83 阅读2分钟

这是我参与「第四届青训营 」笔记创作活动的第5天

如何写好 JAVAScript

图片.png

各司其责,组件封装,过程抽象 要将 html css js 分离

函数式编程方式

为什么要各司其责呢? 图片.png 夜间模式,白天切换案例

图片.png

图片.png

html/css/js 各司其责 **应当避免不必要的由 js 直接操作样式 可以用 class 来表示状态 纯展示类交互寻求零 js 方案

轮播图效果

图片.png 使用 css 绝对定位将图片重叠在同一位置,轮播图切换的状态使用修饰符,轮播图的切换动画使用 CSS transition

图片.png

总结:基本方法

  • 结构设计

  • 展现效果

  • 行为设计

    1. API (功能)
    2. Event (控制流) 组件是指Web页面上抽出来一个个包含模版(HTML)、功能(JS)和样式(CSS)的单元。好的组件具备封装性、正确性、扩展性、复用性。

图片.png

解耦

  • 将控制元素抽取成插件
  • 插件与组件之间通过依赖注入方式建立联系

图片.png

抽象

  • 将组件通用模型抽象出来

总结

  • 组件设计的原则:封装性、正确性、扩展性、复用性

  • 实现组件的步骤:结构设计、展现效果、行为设计

  • 三次重构

    1. 插件化
    2. 模板化
    3. 抽象化(组件框架

过程抽象

过程抽象

  • 用来处理局部细节控制的一些方法
  • 函数式编程思想的基础应用

高阶函数

图片.png

图片.png

图片.png

我们为什么要使用高阶函数呢?

图片.png

编程范式

例子

图片.png

编程范式

总结

  • 过程抽象 / HOF / 装饰器
  • 命令式 / 声明式

写代码最应该关注什么?

  • 风格?
  • 效率?
  • 约定?
  • 使用场景?
  • 设计?

都要关注哈

图片.png

当年的Leftpad事件

/**
   * String.prototype.repeat() polyfill
   https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat#Polyfill
  */
  if (!String.prototype.repeat) {
    String.prototype.repeat = function(count) {
      'use strict';
      if (this == null)
        throw new TypeError('can't convert ' + this + ' to object');

      var str = '' + this;
      // To convert string to integer.
      count = +count;
      // Check NaN
      if (count != count)
        count = 0;

      if (count < 0)
        throw new RangeError('repeat count must be non-negative');

      if (count == Infinity)
        throw new RangeError('repeat count must be less than infinity');

      count = Math.floor(count);
      if (str.length == 0 || count == 0)
        return '';

      // Ensuring count is a 31-bit integer allows us to heavily optimize the
      // main part. But anyway, most current (August 2014) browsers can't handle
      // strings 1 << 28 chars or longer, so:
      if (str.length * count >= 1 << 28)
        throw new RangeError('repeat count must not overflow maximum string size');

      var maxCount = str.length * count;
      count = Math.floor(Math.log(count) / Math.log(2));
      while (count) {
        str += str;
        count--;
      }
      str += str.substring(0, maxCount - str.length);
      return str;
    }
  }

\

图片.png

判断是否是4的幂

\