手写一切。。。

186 阅读1分钟
// 手写bind
function bind2(context = globalThis) { //context是上下文对象
    if(typeof this !=='function') { // 此处的this是原函数
      throw Error('.....')
    }
    var that = this;
    var arg1 = Array.from(arguments).slice(1);
    function fn() {
      var arg2 = Array.from(arguments);
      if (this instanceof fn) {
        that.apply(this, [...arg1, ...arg2]);
      } else {
        that.apply(context, [...arg1, ...arg2]);
      }
    }
    fn.prototype = Object.create(that.prototype);
    return fn;
  }
  
   // 手写new
  function new2(fn, ...args) {
    var obj = Object.create(fn.prototype);
    const res = fn.apply(obj, args);
    return (typeof res === "object" && res !== null) ||
      typeof res === "function"
      ? res
      : obj;
  }

  function Person(name) {
    this.name = name;
  }
  var hh = new2(Person, "zhishao");
  var hhh = new Person("zhishao");
  console.log(hh);
  console.log(hhh);
  
  // 经典原型链题目
  function Foo() {
    getName = function () {
      console.log(1);
    };
    return this;
  }
  Foo.getName = function () {
    console.log(2);
  };
  Foo.prototype.getName = function () {
    console.log(3);
  };

  var getName = function () {
    console.log(4);
  };

  function getName() {
    console.log(5);
  }

  Foo.getName();
  getName(); 
  Foo().getName(); 
  getName(); 
  new Foo.getName();
  new Foo().getName(); 
  new new Foo().getName();