zoukankan      html  css  js  c++  java
  • call,apply,bind实现

    call和apply都是对函数的直接调用,而bind方法返回的仍然是一个函数

    call的实现原理:在方法调用模式下,this 总是指向调用它所在方法的对象,this 的指向与所在方法的调用位置有关,而与方法的声明位置无关(箭头函数特殊)

    利用 this 的机制来实现 call

     1 Function.prototype.mycall = function(thisArg) {
     2     if(typeof this !== 'function') {
     3         throw TypeError(`${this} is not a function`);
     4     }
     5     const args = [...arguments].slice(1);
     6     thisArg = thisArg || window;
     7     thisArg.fn = this;
     8     const result = thisArg.fn(...args);
     9     delete thisArg.fn;
    10     return result;
    11 }

    apply的实现:

     1 Function.prototype.myapply = function(thisArg) {
     2     if(typeof this !== 'function') {
     3         throw TypeError(`${this} is not a function`);
     4     }
     5     thisArg = thisArg || window;
     6     const args = arguments[1];
     7     thisArg.fn = this;
     8     const result = thisArg.fn(...args);
     9     delete thisArg.fn;
    10     return result;
    11 }

    bind实现:封装了 call 的方法改变了 this 的指向并返回一个新的函数

    1 Function.prototype.mybind = function(fun) {
    2     if(typeof this !== 'function') {
    3         throw TypeError('Bind must be called on a function')
    4     }
    5     var self = this;
    6     return function () {
    7         self.apply(fun, arguments);
    8     }
    9 }
  • 相关阅读:
    记一次DRF问题排障
    贷款
    wpf 手指触摸图片放大缩小 设置放大缩小值
    wpf下的图片放大缩小
    WPF 鼠标移动到图片变大,移开还原,单击触发事件效果
    导出压缩
    Sql Server 数据库分页存储过程书写
    Asp.Net Core MVC传值 Asp.Net Core API 前台写法
    MVC下拉框
    Dapper和EF学习
  • 原文地址:https://www.cnblogs.com/vicky24k/p/11888962.html
Copyright © 2011-2022 走看看