前端开发那些事儿

高频手写题目

2021-03-31  本文已影响0人  Angel_6c4e
建议优先掌握:
实现instanceOf
// 实例.__ptoto__ === 类.prototype
function myInstanceof(example, classFunc) {
    let proto = Object.getPrototypeOf(example); //返回指定对象的原型
    while(true) {
        if(proto == null) return false;

        // 在当前实例对象的原型链上,找到了当前类
        if(proto == classFunc.prototype) return true;
        // 沿着原型链__ptoto__一层一层向上查
        proto = Object.getPrototypeof(proto); // 等于proto.__ptoto__
    }
}
new操作符做了这些事:
function myNew(fn, ...args) {
    let instance = Object.create(fn.prototype); //创建一个新对象,使用现有的对象来提供新创建的对象的__proto__。
    let res = fn.apply(instance, args); // 改变this指向

    // 确保返回的是一个对象(万一fn不是构造函数)
    return typeof res === 'object' ? res: instance;
}
实现一个call方法
Function.prototype.myCall = function (context = window) {
  context .func = this;
  let args = Array.from(arguments).slice(1); //从一个类似数组或可迭代对象创建一个新的,浅拷贝的数组实例。
  let res = args.length > 1 ? context.func(...args) : context.func();
  delete context.func;
  return res;
}
实现apply方法
Function.prototype.myApply = function (context = window) {
  context.func = this;
  let res = arguments[1] ? context.func(...argumnets[1]) : context.func();
  delete context.func;
  return res;
}
实现一个bind方法
Function.prototype.myBind = function (context) {
  let cext = JSON.parse(JSON.stringify(context)) || window;
  cext .func = this;
  let args = Array.from(argumnets).slice(1);
  return function () {
    let allArgs= args .concat(Array.from(arguments));
    return allArgs.length ? cext.func(...allArgs) : cext.func();
  }
}
实现一个Promise
class myPromise {
  constructor (fn) {
    this.status = 'pending';
    this.value = undefined;
    this.reason = undefined;

    this.onFulfilled = [];
    this.onRejected = [];

    let resolve = value => {
        if(this.status  === 'pending') {
            this.status  = 'fulfilled';
            this.value = value;
            this.onFulfilled.forEach(fn => fn(value));
        }
    }
    let reject = value => {
      if(this.status === 'pending') {
          this.status = 'rejected';
          this.reason = value;
          this.onRejected.forEach(fn => fn(value))
      }
    }

    try {
        fn(resolve,reject);
    } catch (e) {
        reject(e)
    }
  }
  
  then (onFulfilled,onRejected) {
     if(this.status === 'fulfilled') {
          typeof onFulfilled === 'function' && onFulfilled(this.value);
      }
      if(this.staus === 'rejected') {
          typeof onRejected === 'function' && onRejected(this.reason);
      }
      if(this.status === 'pending') {
          typeof onFulfilled === 'function' && this.onFulfilled.push(this.value);
          typeof onRejected ===  'function' && this.onRejected.push(this.reason);
      }
  }
}

let p = new myPromise ((resolve,reject) => {
    console.log('我是promise的同步代码');
    //异步任务
    $.ajax({
      url:'data.json',
      success:function (data) {
          resolve(data)
      },
      error:function (err) {
          reject(err);
      }
    })
})

p.then((res) => {
  console.log(res);
})
手写原生AJAX
function ajax () {
  let xml = new XMLHttpRequest();
  xml.open('get','https://www.google.com',true);
  xml.onreadystatechange = () => {
    if(xml.readystate === 4) {
        if(xml.status > 200 && xml.status < 300 && xml.status = 304){
             alert(xml.responseText);
        }else {
            alert('Error' + xml.status);
        }
    }
  }
  xml.send();  
}
promise实现AJAX:
function myAjax (url,method) {
  return new Promise((resovle,reject) => {  
      const xhr = new XMLHttpRequest();
      xhr.open(url,method,true);
      xhr.onReadystatechange = function () {
          if(xhr.readyState === 4 ){
              if(xhr.status >200 && xhr.status <300 && xhr.status ===304 ){
                  resolve(xhr.responseText);
              }else if(xhr.status === 404){
                reject(new Error('404'));
              }
          }else{
                reject('请求数据失败!');
          }
      }
      xhr.send(null)
  })
}

上一篇下一篇

猜你喜欢

热点阅读