JavaScript의 일반적인 필기 기능

coldplay.xixi
풀어 주다: 2020-09-18 16:56:04
앞으로
2423명이 탐색했습니다.

JavaScript의 일반적인 필기 기능

관련 학습 권장사항: javascript

1. 흔들림 방지

function debounce(func, ms = 500) {  let timer;  return function (...args) {    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      func.apply(this, args);
    }, ms);
  };
}复制代码
로그인 후 복사

3. new

function throttle(func, ms) {  let canRun = true;  return function (...args) {    if (!canRun) return;
    canRun = false;
    setTimeout(() => {
      func.apply(this, args);
      canRun = true;
    }, ms);
  };
}复制代码
로그인 후 복사

4. 리

5 전화

function myNew(Func) {  const instance = {};  if (Func.prototype) {    Object.setPrototypeOf(instance, Func.prototype);
  }  const res = Func.apply(instance, [].slice.call(arguments, 1));  if (typeof res === "function" || (typeof res === "object" && res !== null)) {    return res;
  }  return instance;
}复制代码
로그인 후 복사

6. apply

Function.prototype.myBind = function (context = globalThis) {  const fn = this;  const args = Array.from(arguments).slice(1);  const newFunc = function () {    if (this instanceof newFunc) {      // 通过 new 调用,绑定 this 为实例对象
      fn.apply(this, args);
    } else {      // 通过普通函数形式调用,绑定 context
      fn.apply(context, args);
    }
  };  // 支持 new 调用方式
  newFunc.prototype = fn.prototype;  return newFunc;
};复制代码
로그인 후 복사

7. 이벤트 버스 | 게시 및 구독 패턴

Function.prototype.myCall = function (context = globalThis) {  // 关键步骤,在 context 上调用方法,触发 this 绑定为 context
  context.fn = this;  let args = [].slice.call(arguments, 1);  let res = context.fn(...args);  delete context.fn;  return res;
};复制代码
로그인 후 복사

9. 매개변수 중 일부만 함수에 전달하고 처리할 함수를 반환합니다. 나머지 매개 변수는 ES5 인스턴스 인스턴스 인스턴스

Function.prototype.myApply = function (context = globalThis) {  // 关键步骤,在 context 上调用方法,触发 this 绑定为 context
  context.fn = this;  let res;  if (arguments[1]) {
    res = context.fn(...arguments[1]);
  } else {
    res = context.fn();
  }  delete context.fn;  return res;
};复制代码
로그인 후 복사
| ee 누구나 추가해도 좋아요~

위 내용은 JavaScript의 일반적인 필기 기능의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:juejin.im
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!