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

时间:2015-03-31 20:05:04

标签: javascript angularjs this bind

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

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类调用,因此我需要将this绑定回welcomeCtrl,因此我使用.bind并且传入welcomeCtrl

当我执行alert(this) welcomeCtrl函数定义提醒时,这应该可以正常工作,但当我alert(this.beginScan)时,我得到Undefined

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

2 个答案:

答案 0 :(得分:1)

每当使用对象的内部函数时(在这种情况下,welcomeCtrlthis引用当前对象。

采用以下示例:

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

答案 1 :(得分:0)

正如@Jesse Kernaghan建议我只是将未经启发的构造函数作为thisParam传递。我通过修改我的服务来修复它,以获取2个参数,一个回调和一个thisParam。然后,我必须从我的指令传入scope作为thisParam,并在我的服务中使用.bind(thisParam)调用回调,现在一切正常。