this理解

函数绑定Function-prototype-bind

  • 将函数绑定到指定环境

    1
    2
    3
    4
    5
    6
    Function.prototype.bind = function(scope){
    var fn = this;
    return function(){
    return fn.apply(scope);
    }
    }
  • 举例1

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    this.x = 9;    // this refers to global "window" object here in the browser
    var module = {
    x: 81,
    getX: function() { return this.x; }
    };

    module.getX(); // 81

    var retrieveX = module.getX;
    retrieveX();
    // 9

    var boundGetX = retrieveX.bind(module);
    boundGetX(); // 81
  • 举例2

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    var foo = {
    x: 3
    }

    var bar = function(){
    console.log(this.x);
    }

    bar(); // undefined

    var boundFunc = bar.bind(foo);

    boundFunc(); // 3