无法使用.bind更改分配给此对象的值
not able to change a value assigned to this object using .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
为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)
调用回调,现在一切都正常了。
相关文章:
- 为什么在Javascript中将一个对象分配给另一个变量也会更改初始对象
- 在运行时使用预先确定的对象分配变量
- Javascript对象分配gottcha
- 通过程序将对象分配给数组
- AngularJS-对象分配不起作用
- 在PHP中为JSON对象分配标识符/名称
- 对象分配在此angularjs控制器中不起作用
- 对象分配 - 更新特定属性
- 将对象分配给另一个对象并保留原始数据
- ES6 对象分配部分项
- 为每个对象分配一个键
- 将函数中的对象分配给变量或调用 setState 没有这个
- 按对象数组中的值为对象分配等级
- 为什么将其他对象分配给内置对象(例如文档、窗口)没有意义
- 将FileReader内部的结果对象分配给变量
- 为Javascript对象分配函数
- Javascript对象分配'他奇怪的行为
- 了解在 JavaScript 中为对象分配函数
- 为CanvasXpress的Json对象分配Javascript数组值
- 只需使用Immutable.js将对象分配给变量,即可克隆新对象