antd5源码分析之classnames库

classnames地址

代码仓库
https://github.com/JedWatson/classnames

源码

可以找到rec/index.js文件

var hasOwn = {}.hasOwnProperty;

function classNames() {
  var classes = [];

  for (var i = 0; i < arguments.length; i++) {
    var arg = arguments[i];
    if (!arg) continue;

    var argType = typeof arg;

    if (argType === 'string' || argType === 'number') {
      classes.push(arg);
    } else if (Array.isArray(arg)) {
      if (arg.length) {
        var inner = classNames.apply(null, arg);
        if (inner) {
          classes.push(inner);
        }
      }
    } else if (argType === 'object') {
      if (arg.toString !== Object.prototype.toString && !arg.toString.toString().includes('[native code]')) {
        classes.push(arg.toString());
        continue;
      }

      for (var key in arg) {
        if (hasOwn.call(arg, key) && arg[key]) {
          classes.push(key);
        }
      }
    }
  }
// 通过join将classes数组转换为字符串,返回;
  return classes.join(' ');
}

分析

片段1

通过arguments获取classnames函数接受的参数
利用for语句循环argument,当参数不存在时,continue继续执行。

  for (var i = 0; i < arguments.length; i++) {
    var arg = arguments[i];
    if (!arg) continue;
 }

片段2

通过typeof来判断参数的类型,只有三种分支结果:

var argType = typeof arg;

string或者number

直接push到classes数组中;

if (argType === 'string' || argType === 'number') {
  classes.push(arg);
}

array

这里是递归调用classNames函数,将数组中的每一项作为参数传入;

if (Array.isArray(arg)) {
      if (arg.length) {
        var inner = classNames.apply(null, arg);
        if (inner) {
          classes.push(inner);
      }
  }
}

object

  • 这里是遍历对象的每一项,如果值为true,则将key作为类名pushclasses数组中;
  • 但是首先这里的处理是先判断argtoString方法是否被重写,如果被重写了,则直接将arg的toString方法的返回值push到classes数组中;
  • -第一个判断是判断argtoString方法是否被重写;
  • 第二个判断是判断Object.prototype.toString方法是否被重写,如果被重写了,则arg的toString方法的返回值一定不会包含[native code]
if (argType === 'object') {
      if (arg.toString !== Object.prototype.toString && !arg.toString.toString().includes('[native code]')) {
        classes.push(arg.toString());
        continue;
      }

      for (var key in arg) {
        if (hasOwn.call(arg, key) && arg[key]) {
          classes.push(key);
        }
      }
}
Function.prototype.toString()  toString()// 方法返回一个表示当前函数源代码的字符串。
console.log(Math.abs.toString());
// Expected output: "function abs() { [native code] }"
console.log({}.toString);//ƒ toString() { [native code] }
console.log({}.toString.toString());// 'function toString() { [native code] }'
console.log(Object.toString);//ƒ toString() { [native code] }
console.log(Object.toString?.toString());//'function toString() { [native code] }'
console.log(Object.prototype.toString);//ƒ toString() { [native code] }
console.log(Object.prototype.toString());//'[object Object]'
console.log(Object.prototype.toString.call('SS'));//'[object String]'
console.log(Object.prototype.toString.call(null));//'[object Null]'

测试

  const class1 = classNames('select-menu') // 'select-menu'
  const class2 = classNames('select-menu', 2) // 'select-menu 2'
  const class3 = classNames({
    "select-box": true,
    "select-class-box": false,
    "ul-box": 'ul-box-w'
  })// 'select-box ul-box'
  // 重写toString方法
  function fun(as) {
    fun.prototype.toString = function () {
      return as
    }
  }

  const class4 = classNames(new fun('oi'))//'oi'

兼容性

CommonJS

CommonJS是Node.js的模块规范,Node.js中使用require来引入模块,使用module.exports来导出模块;

所以这里通过判断module是否存在来判断是否是CommonJS环境,如果是的话,就通过module.exports来导出模块。

AMD

AMD是RequireJS在推广过程中对模块定义的规范化产出,AMD也是一种模块规范,AMD中使用define来定义模块,使用require来引入模块;

所以这里通过判断define是否存在来判断是否是AMD环境,如果是的话,就通过define来定义模块。

window 浏览器环境

window是浏览器中的全局对象,这里并没有判断,直接使用else兜底,因为这个库最终只会在浏览器中使用,所以这里直接使用window来定义模块。

  // CMD模块 支持module
	if (typeof module !== 'undefined' && module.exports) {
		classNames.default = classNames;
		module.exports = classNames;
	} else if (typeof define === 'function' && typeof define.amd === 'object' && define.amd) {
    // AMD模块
		// register as 'classnames', consistent with npm package name
		define('classnames', [], function () {
			return classNames;
		});
	} else {
		window.classNames = classNames;
	}

你可能感兴趣的:(ui组件库,antd5,react.js,javascript)