假设我有一个基本的哑巴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"."这"是承诺,"funcConfigs"直接返回undefined.
我尝试用a来解决这个问题,.resolveWith(this)
但它没有解决这个问题.
如何在此范围上下文中访问实例变量?
在同意的情况下user2864740
,问题很可能是因为this
不是您在show
调用回调时所期望的那样.为了使其正常工作,您需要this
在闭包中捕获正确的(例如var that = this;
),并显式调用它.
换一种说法...
FunctionX.prototype.setup = function() { var that = this; this.getData().then(function () { that.show(); }); }
编辑:为了更清晰的语法(使用underscore.js):
FunctionX.prototype.setup = function() { var that = this; this.getData().then(_.bind(this.show, this)); }