手写 call丶apply丶bind丶new丶Promise

99 阅读2分钟

手写call

// 实现 call 方法
Function.prototype.newCall = function(context, ...args) {
  // 判断是否是undefined和null
  if (typeof context === 'undefined' || context === null) {
    context = window
  }
    context.fn = this;
    context.fn(...args);
    delete context.fn;
}

let foo = {
    value: 100
};

function bar(name) {
    console.log(this.value);
}
// 测试一下
bar.newCall(foo); // 100

手写apply

// 实现 apply 方法
Function.prototype.newApple = function(context, args = []) {
  // 判断是否是undefined和null
  if (typeof context === 'undefined' || context === null) {
    context = window
  }
    context.fn = this;
    context.fn(args);
    delete context.fn;
}

let foo = {
    value: 100
};

function bar(arr) {
    console.log(this.value);
    console.log('arr',arr);    
}
// 测试一下
bar.newApple(foo,['1','2','3']); // 100, ['1','2','3']

手写bind

// 实现 bind 方法
Function.prototype.newBind = function(context, ...args) {
  // 判断是否是undefined和null
  if (context == null) {
    context = window
  }
  // 处理原始值
  if (typeof context !== 'object') {
    context = Object(context)
  }
  const that = this
  return function(...innerArgs) {
    return that.apply(context, [...args, ...innerArgs])
  }
}

let foo = {
    value: 100
};

function bar(arr) {
    console.log(this.value);
    console.log('arr',arr);    
}
// 测试一下
var livebind = bar.newBind(foo, ['1','2','3'])
livebind() // 输出: 100, ['1','2','3']

手写new

// 实现 new 方法
function Person (name, age) {
    this.name = name;
    this.age = age;
}


function newObj(context, ...args) {

  // 获取除了第一个参数以外的所有参数,合并为一个数组
  console.log('...args',args)  // ['live', '18']

  // 1. 创建一个新对象
  var obj = {};
  // 2. 链接到构造函数实例原型原型,这样就可以访问构造函数原型中的属性和方法
  obj.__proto__ = context.prototype;
  // 3. 绑定 this,执行构造函数
  context.apply(obj, args);
  // 4. 返回新对象
  return obj;
};

var person = newObj(Person, 'live', '18')

console.log(person.name) // live
console.log(person.age) // 18

手写Promise

      // 实现一个promise
      class MyPromise {
        // 构造方法
        constructor(live) {
          // 初始化值
          this.initValue();
          // 初始化绑定
          this.initBind();
          // 存储成功和失败的回调
          this.onFulfilledCallbacks = [];
          this.onRejectedCallbacks = [];
          // 执行传进来的函数
          try {
            live(this.resolve, this.reject);
          } catch (error) {
            this.reject(error);
          }
        }

        initValue() {
          // 初始化值
          this.PromiseResult = null; // 终值
          this.PromiseState = "pending"; // 状态
        }

        resolve(value) {
          if (this.PromiseState !== "pending") return;
          // 如果执行resolve,状态变为fulfilled
          this.PromiseState = "fulfilled";
          // 终值为传进来的值
          this.PromiseResult = value;
          this.onFulfilledCallbacks.forEach((fn) => fn(value));
        }

        reject(reason) {
          if (this.PromiseState !== "pending") return;
          // 如果执行reject,状态变为rejected
          this.PromiseState = "rejected";
          // 终值为传进来的reason
          this.PromiseResult = reason;
          this.onRejectedCallbacks.forEach((fn) => fn(reason));
        }

        initBind() {
          this.resolve = this.resolve.bind(this); // 绑定this
          this.reject = this.reject.bind(this); // 绑定this
        }

        then(onFulfilled, onRejected) {
          // 判断回调函数是否为函数
          onFulfilled =
            typeof onFulfilled === "function" ? onFulfilled : (value) => value;
          onRejected =
            typeof onRejected === "function"
              ? onRejected
              : (reason) => {
                  throw reason;
                };

          return new MyPromise((resolve, reject) => {
            const handlePromise = (fn, value) => {
              setTimeout(() => {
                try {
                  const result = fn(value); // 执行回调函数
                  if (result instanceof MyPromise) {
                    // 如果返回的是一个Promise对象,直接将其状态和值传递给新的Promise
                    result.then(resolve, reject);
                  } else {
                    // 如果返回的不是一个Promise对象,直接将其值传递给新的Promise
                    resolve(result);
                  }
                } catch (error) {
                  reject(error);
                }
              });
            };

            // 判断状态
            if (this.PromiseState === "fulfilled") {
              // 调用成功的回调
              handlePromise(onFulfilled, this.PromiseResult);
            } else if (this.PromiseState === "rejected") {
              // 调用失败的回调
              handlePromise(onRejected, this.PromiseResult);
            } else if (this.PromiseState === "pending") {
              // 存储回调
              this.onFulfilledCallbacks.push(() => {
                handlePromise(onFulfilled, this.PromiseResult);
              });
              this.onRejectedCallbacks.push(() => {
                handlePromise(onRejected, this.PromiseResult);
              });
            }
          });
        }
      }

      const test1 = new MyPromise((resolve, reject) => {
        resolve("test1");
      })
      .then((res) => {
        console.log("then1", res);
      })