Function.prototype.bind()

参照原文:Function.prototype.bind() - JavaScript | MDN

MDN bind() 函数的两种应用的示例代码:

  • 创建绑定函数
Function.prototype.bind()_第1张图片
image.png
this.x = 9;
    var module = {
        x: 81,
        getX: function() { return this.x; }
    };

    module.getX(); // 返回 81

    var retrieveX = module.getX;
    retrieveX(); // 返回 9, 在这种情况下,"this"指向全局作用域

    // 创建一个新函数,将"this"绑定到module对象
    // 新手可能会被全局的x变量和module里的属性x所迷惑
    var boundGetX = retrieveX.bind(module);
    boundGetX(); // 返回 81
  • 偏函数(Partial Functions)
Function.prototype.bind()_第2张图片
image.png
function list() {
  return Array.prototype.slice.call(arguments);
}

var list1 = list(1, 2, 3); // [1, 2, 3]

// Create a function with a preset leading argument
var leadingThirtysevenList = list.bind(undefined, 37);

var list2 = leadingThirtysevenList(); // [37]
var list3 = leadingThirtysevenList(1, 2, 3); // [37, 1, 2, 3]

你可能感兴趣的:(Function.prototype.bind())