我正在使用 Angular 开发一个 Web 应用程序,并尝试使用函数的 .bind
方法在我的一个 Controller 的方法上分配 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
为 true 的指令。
由于它是调用该方法的服务,并且不是从 welcomCtrl
类调用的,因此我需要将 this
绑定(bind)回 welcomeCtrl
所以我使用 .bind
并传入 welcomeCtrl
这应该有效,当我执行 alert(this)
时,welcomeCtrl 函数定义会正常发出警报,但是当我执行 alert(this.beginScan)
时,我得到 未定义
我不明白 .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
关于javascript - 无法使用 .bind 更改分配给该对象的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29377580/