면접에서 자주 보는 원본 실현

34535 단어 면접
면접에서 자주 걸리는 손찢기 코드:
  • call/apply/bind
  • instanceof
  • 딥 카피
  • ES5/ES6 기반으로'양방향 귀속'을 실현합니다
  • promise 관련

  • 1.call/apply/bind의 코드 구현


    call

    Function.prototype.call2 = function(context) {
      if (typeof this !== "function") {
        throw new TypeError("Error");
      }
    
      //  window
      context = context || window;
      //  fn
      const { fn } = context;
    
      //  context , this
      context.fn = this;
      const args = [...arguments].slice(1);
      const result = context.fn(...args);
    
      //  fn
      context.fn = fn;
      return result;
    };
    

    apply

    Function.prototype.apply2 = function(context) {
      if (typeof this !== "function") {
        throw new TypeError("Error");
      }
    
      context = context || window;
      const { fn } = context;
    
      context.fn = this;
      let result;
      if (Array.isArray(arguments[1])) {
        //  ... 
        result = context.fn(...arguments[1]);
      } else {
        result = context.fn();
      }
    
      context.fn = fn;
      return result;
    };
    

    bind

    Function.prototype.bind2 = function(context) {
      if (typeof this !== "function") {
        throw new TypeError("Error");
      }
    
      const that = this;
      //  , 
      const args = [...arguments].slice(1);
    
      return function F() {
        //  new , !
        if (this instanceof F) {
          return new that(...args, ...arguments);
        }
    
        // args.concat(...arguments):  
        //  :arguments Array Object,  ...,  
        return that.apply(context, args.concat(...arguments));
      };
    };
    

    2. instanceof 코드 구현

    function instanceof2(left, right) {
      let prototype = right.prototype;
    
      //  left ,  prototype 
      left = left.__proto__;
      while (1) {
        if (left === null || left === undefined) {
          return false;
        }
        if (left === prototype) {
          return true;
        }
        left = left.__proto__;
      }
    }
    

    3. 딥 카피

    function cloneArr(src, target) {
      for (let item of src) {
        if (Array.isArray(item)) {
          target.push(cloneArr(item, []));
        } else if (typeof item === "object") {
          target.push(deepClone(item, {}));
        } else {
          target.push(item);
        }
      }
      return target;
    }
    function deepClone(src, target) {
      const keys = Reflect.ownKeys(src);
      let value = null;
    
      for (let key of keys) {
        value = src[key];
    
        if (Array.isArray(value)) {
          target[key] = cloneArr(value, []);
        } else if (typeof value === "object") {
          //  ,  
          target[key] = deepClone(value, {});
        } else {
          target[key] = value;
        }
      }
    
      return target;
    }
    

    4. ES5/ES6 기반 "양방향 바인딩"


    ES5의 Object.defineProperty()

    
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <title>Documenttitle>
        <script>
          const obj = {
            value: ""
          };
    
          function onKeyUp(event) {
            obj.value = event.target.value;
          }
    
          //   obj.value  
          Object.defineProperty(obj, "value", {
            get: function() {
              return value;
            },
            set: function(newValue) {
              value = newValue;
              document.querySelector("#value").innerHTML = newValue; //  
              document.querySelector("input").value = newValue; //  
            }
          });
        script>
      head>
      <body>
        <p><span id="value">span>p>
        <input type="text" onkeyup="onKeyUp(event)" />
      body>
    html>
    

    ES6의 proxy

    
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>Documenttitle>
      <script>
        const obj = {}
    
        const newObj = new Proxy(obj, {
          get: function(target, key, receiver) {
            return Reflect.get(target, key, receiver)
          },
          set: function(target, key, value, receiver) {
            if(key === 'value') {
              document.querySelector('#value').innerHTML = value
              document.querySelector('input').value = value
            }
            return Reflect.set(target, key, value, receiver)
          }
        })
    
        function onKeyUp(event) {
          newObj.value = event.target.value
        }
    
      script>
    head>
    <body>
      <p><span id="value">span>
      p>
      <input type="text" onkeyup="onKeyUp(event)">
    body>
    html>
    

    좋은 웹페이지 즐겨찾기