前端高频手写题

45 阅读1分钟
  1. call、bind、apply的实现
  Function.prototype.myCall = function (context, ...args) {
    context = context ?? window;
    const type = typeof context;

    if (!["object", "function"].includes(type)) {
      if (/^(symbol|bigint)$/.test(type)) {
        context = Object(context);
      } else {
        context = new context.constructor(context);
      }
    }

    const fn = Symbol("fn");
    context[fn] = this;
    const result = context[fn](...args);
    delete context[fn];

    return result;
  };

  const obj = {
    value: 1,
    [Symbol("fn")]: foo,
  };

  function foo() {
    console.log(this, " this");
  }

  foo.myCall(Symbol("haha"));
  foo.myCall(null);
  foo.myCall(0);
  1. new的实现
function _new(Func, ...args) {
    // 创建{},让__proto__ = 第一参数 基于一个已有的对象创建新对象,新对象会继承原型对象的属性和方法
    const obj = Object.create(Func.prototype);
    const result = Func.apply(obj, args);

    if(result !== null && ["object", "function"].includes(typeof result)) {
      return result;
    }
    return obj;
}

function Dog(age) {
    this.age = age
    // return () => {
    //   console.log(111);
    // }
}
Dog.prototype.say = function() {
    console.log("haha");
}
const d = newMock(Dog, 18)
// const d = new Dog(18)
d.say()

console.log(d);

3.localStorage 实现缓存

  const setStorage = (key, value, expiredTime) => {
    try {
      localStorage.setItem(key, JSON.stringify({ expiredTime,  value}));
      return true;
    } catch (err) {
      return false;
    }
  };
  const getStorage = (key) => {
    try {
      const data = localStorage.getItem(key);
      const now = Date.now();
      const d = JSON.parse(data || "{}");
      if (d.expiredTime > now) {
        return d.value;
      }
      localStorage.removeItem(key);
      return null
    } catch(err) {
      return null
    }
  };