高频手写题目

作者: Angel_6c4e | 来源:发表于2021-03-31 15:56 被阅读0次
    建议优先掌握:
    • instanceof - 考察对原型链的理解
    • new - 对创建对象实例过程的理解
    • call/apply/bind - 对this指向的理解
    • 手写promise - 对异步的理解
    • 手写原生ajax - 对ajax原理和http请求方式的理解,重点是get和post请求的实现
    实现instanceOf
    • 思路:
    • 步骤1:先取得当前类的原型,当前实例对象的原型链
    • 步骤2:一直循环(执行原型链的查找机制)
    • 取得当前实例对象原型链的原型链(proto = proto.proto,沿着原型链一直向上查找)
    • 如果 当前实例的原型链proto上找到了当前类的原型prototype,则返回 true
    • 如果 一直找到Object.prototype.proto == null,Object的基类(null)上面都没找到,则返回 false
    // 实例.__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操作符做了这些事:
    • 创建一个全新的对象
    • 这个对象的proto要指向构造函数的原型prototype
    • 执行构造函数,使用 call/apply 改变 this 的指向
    • 返回值为object类型则作为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
    • 步骤
    • 创建 XMLHttpRequest 实例
    • 发出 HTTP 请求
    • 服务器返回 XML 格式的字符串
    • JS 解析 XML,并更新局部页面
    • 不过随着历史进程的推进,XML 已经被淘汰,取而代之的是 JSON。
    • 了解了属性和方法之后,根据 AJAX 的步骤,手写最简单的 GET 请求。
    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:
    • 返回一个新的Promise实例
    • 创建XMLHttpRequest异步对象
    • 调用open方法,打开url,与服务器建立链接(发送前的一些处理)
    • 监听Ajax状态信息
    • 如果xhr.readyState == 4(表示服务器响应完成,可以获取使用服务器的响应了)
    • xhr.status == 200,返回resolve状态
    • xhr.status == 404,返回reject状态
    • xhr.readyState !== 4,把请求主体的信息基于send发送给服务器
    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)
      })
    }
    
    

    相关文章

      网友评论

        本文标题:高频手写题目

        本文链接:https://www.haomeiwen.com/subject/kskocltx.html