📖
blog
  • README
  • JavaScript
    • 元素的宽高位置信息梳理
    • dom-align 源码浅析
    • Event Loop
    • 函数实参为对象时的陷阱
    • export 与 utils 方法书写规范
    • 手写 Promise 及相关代码理解
    • call,apply,bind 等函数的模拟实现
    • JavaScript继承
    • JavaScript 数据类型与类型判断
    • for..of 和 for..in 的区别
    • 写给自己看的 next 函数
    • JS 可选链与双问号
    • mouseenter 与 mouseover 事件的区别
    • Immutable相关知识
  • CSS
    • 不简单的 z-index
    • 两列布局,三列布局
    • CSS 居中方案整理
    • CSS 像素,设备像素,2倍图梳理
    • iconfont 的使用
  • Node JS
    • 实现简易的 express
  • React 核心知识点整理
    • 高阶组件
    • React 事件处理
    • React Hooks
    • React Context
  • React 状态管理
    • Redux 基础概念
    • Redux 中间件和异步操作
    • Redux Saga
    • Redux 只能有一个 store 对象嘛
  • React 开发实践
    • Ant Design Menu 组件的使用与深入
    • 讲讲吸顶效果与 react sticky
    • 基于 express,搭建 react 的开发环境
    • 通过 antd input 组件分析受控与非受控组件
    • DebounceClick 组件
    • react component Align 组件分析
    • React Portal 之事件冒泡
    • React Transition Group 源码浅析
    • React.cloneElement 父组件向子组件注入 props
    • 一次 Align 组件的问题记录
    • 如何知道子组件的类型
    • React Router 源码简单分析
    • React Redux 源码简单分析
  • Vue.js
    • Vue.js 概览
    • scoped 样式中的 deep
  • TypeScript 语法
    • 基础类型
    • 变量声明
    • 接口
    • 类
    • 函数
    • 泛型
    • 枚举
    • 类型推论
    • 类型兼容性
    • 高级类型
    • Symbol
    • 迭代器和生成器
    • 模块
    • 命名空间
    • JSX
  • 玩转 webpack
    • 第一章: webpack 与构建发展简史
    • 第二章:webpack基础用法
    • 第三章:webpack进阶用法
    • 第四章:编写可维护的 webpack 构建配置
    • 第五章:webpack构建速度和体积优化策略
    • 第六章:通过源代码掌握webpack打包原理
    • 第七章:编写Loader和插件
  • webpack 实践
    • 如何配置 output.library
  • 测试
    • 初识代码测试
    • Jest 中 如何测试 setTimeout
    • Jest Enzyme React 测试实践记录
  • WEB 开发,过往工作沉淀
    • Web安全(DVWA)
    • 内存泄露与事件移除的必要性
    • url to pdf api 与 服务部署踩坑记录
    • 前端调试指南
    • Markdown 转 email
    • github travis ci 自动部署
    • 浏览器缓存知识梳理
    • WEB 系统登录相关知识梳理
    • 将-Axios-请求参数和返回值进行格式化
    • source-map与源码调试
    • HTTPS
    • 使用 rollup 打造自己的 npm 包 (全流程)
    • father-build 是如何工作的
  • 书籍
    • 图解 HTTP 协议
    • 编写可维护的 JavaScript
    • 鸟哥的 Linux 私房菜
    • JavaScript Promise迷你书
  • Linux
    • vimtutor
    • CURL 使用指南
  • Nginx
    • 一次 nginx 分享
  • Git
    • Git Commit Message 须知
    • .gitignore 模板
    • git tag标签
  • 摄影
    • 摄影基础知识
    • 手机摄影从小白到大师
  • 翻译
    • log4js
    • log4js-node
    • 介绍GitLab上的CI/CD
    • 为GitLab Pages创建并调整GitLab CI/CD
    • 关于 rel=noopener
    • AngularJS 团队 Git 提交信息约定
    • JSON Schema
  • Lifehack
    • 20 个 Google 搜索 Tips 来高效使用 Google
    • 37 个高级 Google 搜索 Tips
Powered by GitBook
On this page
  • 前言
  • 1. call
  • 2. apply
  • 3. bind
  • 4. new
  • 5. clone
  • 6. debounce
  • 7. throttle

Was this helpful?

  1. JavaScript

call,apply,bind 等函数的模拟实现

Previous手写 Promise 及相关代码理解NextJavaScript继承

Last updated 4 years ago

Was this helpful?

前言

网上的面试题通常都会涉及各种函数的模拟实现,一开始的态度都是“嗤之以鼻”,要么觉得没意义(实际工作中都是用成熟开源的代码),要么觉得这样做只是为了迎合面试。

但是最近查看相关资料的时候,才意识到其实不单纯是应付面试,另一方面这也是对于 JavaScript 基础的考察。

1. call

指定 this 和 若干参数值的情况下,调用某个函数或者方法

参考:

注意:

  • 函数具有返回值

Function.prototype.call = function(...args){
    const context = args[0] || window;
    const arg = args.slice(1);
    context.fn = this;
    const result = context.fn(...arg);
    delete context.fn;
    return result;
}

2. apply

指定 this 和 若干参数值的情况下,调用某个函数或者方法,区别于 call, 参数值以数组形式提供

注意:

  • 函数具有返回值

Function.prototype.apply = function(context, args = []) {
    context = context || window;
    context.fn = this;
    const result = context.fn(...args);
    delete context.fn;
    return result;
}

3. bind

指定 this 以及若干参数值的情况下,返回一个新的函数

注意:

  • bind时接受的额外参数,应该作为实际调用时的 “前参数”

  • 如果调用bind的不是函数,应该报错

  • 如果bind之后的函数,别当作 Constructor 构造函数使用,那么应该使用构造函数返回的实例, 作为 this。

  • 如果原来函数的 prototype 上具有方法或者属性,应该原样复制一份。同时,为了防止修改新的 prototype 会影响到原有函数的 prototype, 应该使用 NOOP 函数进行原型链的链接。

Function.prototype.bind = function(...args){
    if(typeof this !== 'function') {
        throw new Error('Function.prototype.bind - what to be bound is not a function');
    }
    const fn = this;
    const context = args[0] || window;
    const arg = args.slice(1);
    const returnFun =  function(...innerArgs) {
        const newContext = context;
        if(this instanceof returnFun) {
            // it means, function is called as Constructor
            newContext = this;
        }
        return fn.apply(
            newContext,
            [].concat(arg, innerArgs)
        );
    }
    function NOOP() {}
    NOOP.prototype = this.prototype;
    returnFun.prototype = new NOOP();
    return returnFun;
}

4. new

注意:

  • 返回对象的原型链需要连接到构造函数的prototype上

  • 如果构造函数返回了对象,则直接返回该对象,否则返回新建的对象

function objectFactory(Constructor, ...args) {
    const obj = {};
    const ret = Constructor.apply(obj,args)
    obj.__proto__ = Constructor.prototype;
    return typeof ret === 'object' ? ret : obj;
}

5. clone

深拷贝浅拷贝

注意:

  • 深拷贝的情况,如果属性值是对象,则进行递归

function clone(obj, isDeep) {
    if(typeof obj !== 'object') {
        throw new Error('clone: the arguments[0] should be an object');
    }
    const newObj = obj instanceof Array ? [] : {};
    Object.keys(obj).forEach(key => {
        if(isDeep && typeof obj[key] === 'object') {
            newObj[key] = clone(obj[key])
        } else {
            newObj[key] = obj[key]
        }
    })
    return newObj;
}

6. debounce

防抖,即 wait 时间之内多次触发函数,最终函数之后执行一次

注意:

  • setTimeout 中函数的 this 默认为 window 或者 undefined,因此需要先用 context 保存真正的 this 值。

function debounce(fn, wait, isImmediate) {
    let timer = null;
    return function(...args) {
        const context = this;
        clearTimeout(timer);
        if(isImmediate) {
            const callNow = !timer;
            timer = setTimeout(function(){
                timer = null
            }, wait)
            if(callNow) {
                fn.apply(context, args)
            }
        } else {
            // this in setTimeout will be window or undefined
            time = setTimeout(function() {
                fn.apply(context, args)
            }, wait)    
        }
    }
}

7. throttle

节流,即频繁触发函数,每隔 wait 时间就会触发一次函数的执行

实现方式:

  1. 时间戳法

function throttle(fn,wait) {
    let previous = 0;
    return function(...args) {
        const now = Date.now();
        const context = this;
        if(now - previous > wait) {
            fn.apply(context, args);
            previous = now;
        }
    } 
}
  1. 定时器法

function throttle(fn, wait) {
    let timer = null;
    return function(...args) {
        const context = this;
        if(!timer) {
            timer = setTimeout(() => {
                fn.apply(context, args);
                timer = null;
            }, wait)
        }
    }
}

参考:

参考:

参考:

参考:

参考:

https://github.com/mqyqingfeng/Blog/issues/11
https://github.com/mqyqingfeng/Blog/issues/11
https://github.com/mqyqingfeng/Blog/issues/12
https://github.com/mqyqingfeng/Blog/issues/13
https://github.com/mqyqingfeng/Blog/issues/22
https://github.com/mqyqingfeng/Blog/issues/26