Object.create原理

186 阅读1分钟

01 分 析

语法: Object.create(proto[,propertiesObject])

参数

proto 创建对象的原型,表示要继承的对象

propertiesObject(可选 ) 也是一个对象,用于对新创建的对象进行初始化

注:Object.create(null) 创建的对象是一个空对象,在该对象上没有继承 Object.prototype 原型链上的属性或者方法

Object.create=function(o){
 function F(){};
 F.prototype=o;
 return new F();
}

在项目中实战

let util = {
        uuid: function (len, radix) {
          var chars = uuidCharts,
            uuid = [],
            i;
          radix = radix || chars.length;
          len = len || 16;
          if (len) {
            // Compact form
            for (i = 0; i < len; i++)
              uuid[i] = chars[0 | (Math.random() * radix)];
          } else {
            // rfc4122, version 4 form
            var r;

            // rfc4122 requires these characters
            uuid[8] = uuid[13] = uuid[18] = uuid[23] = "";
            uuid[14] = "4";

            // Fill in random data.  At i==19 set the high bits of clock sequence as
            // per rfc4122, sec. 4.1.5
            for (i = 0; i < 36; i++) {
              if (!uuid[i]) {
                r = 0 | (Math.random() * 16);
                uuid[i] = chars[i == 19 ? (r & 0x3) | 0x8 : r];
              }
            }
          }

          return uuid.join("");
        },
        deepClone: function (target, source, map = new WeakMap()) {
          if (
            typeof source !== "object" ||
            source instanceof Date ||
            source instanceof RegExp ||
            source === null ||
            typeof source === "number"
          ) {
            return source;
          }
          if (map.get(source)) {
            return map.get(source);
          }
          let obj = Array.isArray(source) ? [] : {};
          for (const key in source) {
            map.set(source, obj);
            if (Object.hasOwnProperty.call(source, key)) {
              obj[key] = dsf.deepClone(
                target,
                source[key],
                (map = new WeakMap())
              );
              target[key] = dsf.deepClone(
                target,
                source[key],
                (map = new WeakMap())
              );
            }
          }
          return obj;
        },
      };
      window.dsf = Object.create(util);
      let copy = {
        http: function () {},
        base64: function () {},
        md: function () {},
      };
      dsf.deepClone(dsf, copy);
      console.log("dsf", dsf);