admin管理员组文章数量:1333201
I have the following javascript object, somewhat pseudocode:
{
dateField: new Date(),
addMinutes:function(numMinutes)
{
CallWebService(numMinutes, function{alert(this.dateField; });
}
}
The problem is the scope of the callback function in CallWebService doesn't see the dateField property of the object. Is there a way I can access it? Thanks!
I have the following javascript object, somewhat pseudocode:
{
dateField: new Date(),
addMinutes:function(numMinutes)
{
CallWebService(numMinutes, function{alert(this.dateField; });
}
}
The problem is the scope of the callback function in CallWebService doesn't see the dateField property of the object. Is there a way I can access it? Thanks!
Share Improve this question edited Jul 6, 2010 at 16:25 gblazex 50.1k12 gold badges99 silver badges92 bronze badges asked Jul 6, 2010 at 16:18 extnoobextnoob 1094 silver badges8 bronze badges3 Answers
Reset to default 8You need to preserve the context (the this
value) of the addMinutes
function.
There are several ways to achieve it, the most easy one is to simply store a reference of this
on a variable, that variable will be available to the scope of the callback function, e.g.:
var obj = {
dateField: new Date(),
addMinutes: function(numMinutes) {
var instance = this;
CallWebService(numMinutes, function () {
alert(instance.dateField);
});
}
};
The issue is that the callback is likely setting the scope of the callback function, if you use apply or call you can force the scope. You can do this with something like this:
{
dateField: new Date(),
addMinutes: function (numMinutes) {
var self = this;
var success = function () {
alert(this.dateField;);
};
CallWebService(numMinutes, function () { success.apply(self); });
}
}
You can access any property(i.e variable or function) of an object inside that object scope by using the dot(.) operator. So you can use like this:
var obj = { dateField: new Date(), addMinutes: function(numMinutes) { callWebService(numMinutes, function() { alert(obj.dateField); }); } }
Here 'dateField' variable of the object 'obj' is accessible inside that object scope using the dot operator like 'obj.dateField'. I think this will help you to solve your problem, let me know if you are not clear with the code shown above.
本文标签: Javascript Nested Functions ScopeStack Overflow
版权声明:本文标题:Javascript Nested Functions Scope - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742224115a2435705.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论