我有这个:
var MyObject = function(){
this.url = "monurl";
this.mavar = "";
this.Load = function(){
var callback = {
success: function(o){
mavar = o.responseXML.getElementsByTagName("montag")[0].firstChild.nodeValue;
}
}
YAHOO.util.Connect.asyncRequest('GET',url,callback);
} }
无法访问mavar变量。我怎么能这样做?
答案 0 :(得分:1)
我相信你可以为回调设置范围参数。所以你应该能够做类似以下的事情。
var MyObject = function(){
this.url = "monurl";
this.mavar = "";
this.Load = function(){
var callback = {
success: function(o){
this.mavar = o.responseXML.getElementsByTagName("montag")[0].firstChild.nodeValue;
},
scope: this
}
YAHOO.util.Connect.asyncRequest('GET', this.url, callback);
} }
答案 1 :(得分:0)
保存this
变量:
var MyObject = function() {
this.url = "monurl";
this.mavar = "";
this.Load = function() {
var me = this;
var callback = {
success: function(o) {
me.mavar = o.responseXML.getElementsByTagName("montag")[0].firstChild.nodeValue;
}
}
YAHOO.util.Connect.asyncRequest('GET',url,callback);
}
}
答案 2 :(得分:0)
你也可以这样做:
var MyObject = new function(){
this.url = "monurl";
this.mavar = "";
this.Load =
(function(that){
return function(){
var callback = {
success: function(o){
that.mavar = o.responseXML.getElementsByTagName("montag")[0].firstChild.nodeValue;
}
}
YAHOO.util.Connect.asyncRequest('GET',url,callback);
}
})(this);
};
答案 3 :(得分:0)
在我的对象中,我添加了一个引用它的变量:
var selfMyObject = this;
我在成功回调中将this.mavar替换为selfMyObject.mavar,它运行正常。
答案 4 :(得分:0)
处理此问题的最佳方法是让YUI进行范围校正,因为内置支持。这是文档页面,告诉您如何执行此操作。 http://developer.yahoo.com/yui/connection/#scope
var MyObject = function() {
this.url = "monurl";
this.mavar = "";
this.Load = function() {
var callback = {
success: function(o){
this.mavar = o.responseXML.getElementsByTagName("montag")[0].firstChild.nodeValue;
},
scope: this
}
YAHOO.util.Connect.asyncRequest('GET', url, callback);
}
}