美文网首页
js实现bind方法

js实现bind方法

作者: Victor_818 | 来源:发表于2019-05-13 14:15 被阅读0次

    方法一:

    支持传参
    Function.prototype.my_bind = function() {
          var self = this, // 保存原函数
            context = Array.prototype.shift.call(arguments), // 保存需要绑定的this上下文
            // 上一行等价于 context = [].shift.call(arguments);
            args = Array.prototype.slice.call(arguments); // 剩余的参数转为数组
          return function() { // 返回一个新函数
            self.apply(context, Array.prototype.concat.call(args, Array.prototype.slice.call(arguments)));
          }
        }
    function a(m, n, o) {
        console.log(this.name + ' ' + m + ' ' + n + ' ' + o);
      }
    
      var b = {
        name: 'kong'
      };
    
      a.my_bind(b, 7, 8, 9)();   // kong 7 8 9
    

    方法二:

    // 不支持传参
    Function.prototype.my_bind = function(target){
        return ()=>{
            console.log(target)
            this.call(target);
        }
    }
    function a(m, n, o) {
        console.log(this.name + ' ' + m + ' ' + n + ' ' + o);
      }
    
      var b = {
        name: 'kong'
      };
    
      a.my_bind(b, 7, 8, 9)();   // kong  undefined undefined undefined
    

    相关文章

      网友评论

          本文标题:js实现bind方法

          本文链接:https://www.haomeiwen.com/subject/nnblaqtx.html