美文网首页
2018-09-13

2018-09-13

作者: wlianfu | 来源:发表于2018-09-13 09:33 被阅读6次

    bind 的使用示例

    var foo = { value: 1 };
    function bar() {
      console.log(this.value);
    }
    var bindFoo = bar.bind(foo);
    bindFoo();  // 1
    

    bind 也可以传参

    var foo = { value: 1 };
    function bar(name, age) {
      console.log(this.value);
      console.log(name);
      console.log(age);
    }
    var bindFoo = bar.bind(foo, 'daisy');
    bindFoo('18'); // 1, daisy, 18
    

    摘自: https://segmentfault.com/a/1190000009271416

    Function.prototype.bind2 = function (context) {
    
        if (typeof this !== "function") {
          throw new Error("Function.prototype.bind - what is trying to be bound is not callable");
        }
    
        var self = this;
        var args = Array.prototype.slice.call(arguments, 1);
        var fNOP = function () {};
    
        var fbound = function () {
            self.apply(this instanceof self ? this : context, args.concat(Array.prototype.slice.call(arguments)));
        }
    
        fNOP.prototype = this.prototype;
        fbound.prototype = new fNOP();
    
        return fbound;
    
    }
    

    相关文章

      网友评论

          本文标题:2018-09-13

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