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

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

本文关键字:对象 分配 bind      更新时间:2023-09-26

我正在使用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为true的指令。

由于它是调用方法的服务,并且不是从welcomCtrl类调用的,所以我需要将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)调用回调,现在一切都正常了。