• js学习-apply,call,bind的实现


    目录

    apply

    简单说:构建一个和调用aplly函数一样的字符串,用eval执行,完了之后删除掉,最后返回执行的结果。

    Function.prototype.applyCopy = function() {
      var obj = arguments[0];
      obj.fn = this;
      var args = arguments[1];
    
      if(!args || args.length == 0) return obj.fn();
    
      // obj.fn参数
      var argsStr = '';
    
      for(var i in args) {
        argsStr += '"' + arguments[1][i] + '",';
      }
    
      var result = eval('obj.fn('+argsStr.replace(/,$/, '')+')');
      
      delete obj.fn;
      return result;
    };  
    

    call

    Function.prototype.callCopy = function() {
      var obj = [].shift.applyCopy(arguments);
      return this.applyCopy(obj, arguments);
    }
    

    bind

    Function.prototype.bindCopy = function() {
      var _this = this;
      var obj = arguments[0];
      return function() {
        return _this.applyCopy(obj, arguments);
      }
    }
    

    demo

    var s = {
      desc: 's.desc',
      name: '你好',
    }
    
    var name = 'window';
    var desc = 'window => this'
    
    function sayHi(age, type) {
      return {
        name: this.name,
        desc: this.desc,
        age: age,
        type: type
      }
    }
    
    console.log(sayHi(12,'sayHi'));
    console.log(sayHi.applyCopy(s, [12, 'applyCopy']));
    console.log(sayHi.callCopy(s, 12, 'callCopy'));
    console.log(sayHi.bindCopy(s)(12, 'bindCopy'));
    

    总结:apply是基础,call,bind都是在apply的基础上实现的。

  • 相关阅读:
    LPC 网络编程
    LPC 语言基础
    (lua) 基于cocos 的插入光效
    lua_table 学习
    lua 语言基础
    C++ 三大特性:封装、继承、多态性
    C++的编译预处理
    C++ 用变量定义数组
    C++ STL常用容器浅析
    拦截器的文章 写的可以!
  • 原文地址:https://www.cnblogs.com/meetqy/p/11848475.html
Copyright © 2020-2023  润新知