无法使用 .bind 更改分配给该对象的值

not able to change a value assigned to this object using .bind

我正在使用 angular 开发 Web 应用程序,我正在尝试使用函数的 .bind 方法将 this 值分配给我的一个控制器的方法。它看起来像这样:

var welcomeCtrl = function (userManager) {
  this.partnerName = userManager.getName('partner');
  this.yourName = userManager.getName('you');
  this.beginScan = false;
  var self = this;
};

welcomeCtrl.prototype.scanThumb = function (callback) {
  function doScan() {
    alert(this);
    alert(this.beginScan);
    this.finishedScanning = callback;
    this.beginScan = true;
  }

  doScan.bind(welcomeCtrl)();

};

所以发生的事情是指令将 scanThumb 方法传递给执行它的服务,然后应该触发另一个指令等待 this.beginScan 为真。

因为调用该方法的服务不是从 welcomCtrl class 调用的,所以我需要将 this 绑定回 welcomeCtrl 所以我使用.bind 并传入 welcomeCtrl

这应该有效,当我执行 alert(this) 时,welcomeCtrl 函数定义警报正常,但是当我执行 alert(this.beginScan) 时,我得到 Undefined

我是不是不明白 .bind 方法在这种情况下是如何工作的?

每当您使用对象的内部函数(在本例中,welcomeCtrl)时,this 指的是当前对象。

举个例子:

var Foo = function(){
  this.thing = 'bar';
}

Foo.prototype.setThing = function(newthing){
  //our inner function
  function doInnerThing(){
    //this is now bound to our current Foo instance
    console.log(this);
    //setting our current Foo.thing to new value
    this.thing = newthing;  
  };
  //fire function, bound to current object scope (Foo)
  doInnerThing.bind(this)();
};

Foo.prototype.doThing = function(){
  alert(this.thing);
};

var newFoo = new Foo();
var newFoo2 = new Foo();

newFoo.setThing('newFoo');
newFoo.doThing(); //alerts 'newFoo', the overridden value


newFoo2.doThing();//alerts 'bar', the base value

正如@Jesse Kernaghan 所建议的那样,我只是将未启动的构造函数作为 thisParam 传递。我通过修改我的服务以采用 2 个参数、一个回调和一个 thisParam 来修复此问题。然后我不得不从我的指令中将 scope 作为 thisParam 传递,并在我的服务中使用 .bind(thisParam) 调用回调,现在一切正常。