【发布时间】:2013-12-03 22:14:33
【问题描述】:
假设我有一个基本的哑 javascript 类:
var FunctionX = function(configs) {
this.funcConfigs = configs;
}
FunctionX.prototype.getData = function() {
return $.get('/url');
}
FunctionX.prototype.show = function(promise) {
console.log(this.funcConfigs); // <-- this here is the promise itself, I'm looking to get the instance's configs
}
FunctionX.prototype.setup = function() {
this.GetData().then(show);
}
var f = new FunctionX({ "a": "b" });
f.setup();
现在我正在这里尝试在 show 函数中访问实例变量“funcConfig”。 “this”是promise,“funcConfigs”直接返回undefined。
我尝试使用.resolveWith(this) 解决此问题,但它没有解决此问题。
如何访问此范围上下文中的实例变量?
【问题讨论】:
-
与promise无关,仅
this在不同上下文调用的函数中。 -
我放回 jquery-deferred 标记以使用
resolveWith,它试图从相反的方式解决问题(例如,指定上下文,不绑定到现有上下文)。如果这“不能解决问题”,那么在使用resolveWith的上下文中,this已经是错误的。 -
该代码真的运行了吗?我可以理解
this.getData().then(this.show);(尽管您可能仍然有同样的问题)。
标签: javascript this jquery-deferred