为什么在我可以通过引用复制另一个方法时使用bind()?

时间:2016-07-05 23:10:47

标签: javascript

我正在观看bind()教程,其中提供了以下代码作为bind() - http://jsbin.com/pugogiqupu/1/edit?js,console的示例:

function doubleScore() {
  this.score *= 2;
}

function Game() {
  this.score = 1;
  this.double = doubleScore.bind(this);
  this.printScore = function() {
    console.log(this.score);
  }
}

var game = new Game();
game.score = 3;
game.printScore(); // Consoles out: 3
game.double();
game.printScore(); // Consoles out: 6

var game2 = new Game();
game2.score = 4;
game2.printScore(); // Consoles out: 4
game2.double();
game2.printScore(); // Consoles out: 8

我注意到,如果我省略.bind(this)并简单地引用该函数而不绑定它,它仍然可以工作。

function doubleScore() {
  this.score *= 2;
}

function Game() {
  this.score = 1;
  this.double = doubleScore;
  this.printScore = function() {
    console.log(this.score);
  }
}

var game = new Game();
game.score = 3;
game.printScore(); // Consoles out: 3
game.double();
game.printScore(); // Consoles out: 6

var game2 = new Game();
game2.score = 4;
game2.printScore(); // Consoles out: 4
game2.double();
game2.printScore(); // Consoles out: 8

为什么在这种情况下使用bind()有益?我错过了什么?

编辑:如果任何一种方法都可以处理这种情况,那么有没有办法重新编写我的示例,说明如何使用bind()?

2 个答案:

答案 0 :(得分:3)

仅当您想要使用.bind语法(自动设置object.method()属性)调用方法时,才需要

this。在您提供的示例中,使用.bind没有任何好处。

一个有点人为的例子, 需要.bind

function doubleScore() {
  this.score *= 2;
}

function tripleScore() {
  this.score *= 3;
}

function Game() {
  this.score = 1;
  this.double = doubleScore.bind(this);
  this.triple = tripleScore.bind(this);
}

var game = new Game();

const multiply = someCondition ? game.double : game.triple;
// Calls the method without context; "this" will only refer
// to "game" because of the binding
multiply();

如果您希望将multiply移至某些不了解game的其他功能或流程,例如,事件处理程序:

// Multiply by some factor when the user clicks a button
document.getElementById('multiplyButton')
  .addEventListener("click", multiply);

答案 1 :(得分:0)

手动绑定this在回调时尤为有趣,其中上下文会发生变化:

var X = function() {
  this.a = 1;
}

X.prototype.print = function() {
  setTimeout(function() { console.log(this.a) }, 100);
}

new X().print() // undefined

<强>与

var X = function() {
  this.a = 1;
}

X.prototype.print = function() {
  setTimeout(function() { console.log(this.a) }.bind(this), 100);
}

new X().print() // 1

为了能够从回调中访问对象,绑定函数的上下文可能是有意义的。