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

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

  • 创建绑定函数

image.png

  1. this.x = 9;
  2. var module = {
  3. x: 81,
  4. getX: function() { return this.x; }
  5. };
  6. module.getX(); // 返回 81
  7. var retrieveX = module.getX;
  8. retrieveX(); // 返回 9, 在这种情况下,"this"指向全局作用域
  9. // 创建一个新函数,将"this"绑定到module对象
  10. // 新手可能会被全局的x变量和module里的属性x所迷惑
  11. var boundGetX = retrieveX.bind(module);
  12. boundGetX(); // 返回 81
  • 偏函数(Partial Functions)

image.png

  1. function list() {
  2. return Array.prototype.slice.call(arguments);
  3. }
  4. var list1 = list(1, 2, 3); // [1, 2, 3]
  5. // Create a function with a preset leading argument
  6. var leadingThirtysevenList = list.bind(undefined, 37);
  7. var list2 = leadingThirtysevenList(); // [37]
  8. var list3 = leadingThirtysevenList(1, 2, 3); // [37, 1, 2, 3]