作者xamous (一天死去一点)
看板Ajax
标题[问题] Javascript object 的问题
时间Wed Dec 26 21:16:36 2007
我有一个自订物件,会透过 Ajax 来 update 内部的一些值,我把问题简化如下:
MyObject = function(initVal) {
this.val = initVal;
}
//a method
MyObject.prototype.load = function(url) {
//使用 prototype.js 的 Ajax.Request 物件
new Ajax.Request(
url, {
method: 'get',
onSucccess: function(t) {
this.val = t.responseText; // <- problem here!!
}
});
}
//use
var myObj = MyObject.new('0'); //init with '0'
myObj.load('
http://some-url/response_text_is_1');
alert(myObj.val); //期望是 '1',但还是初始值 '0'
问题就是 this.val = t.responseText; 这一行,因为这是在一个 callback
function 里,所以 this.val 存取到的是这个 function 内部的变数,而不
是 MyObject 里的 MyObject.val 这个变数,即使执行 MyObject.load()
也更新不到它的成员变数(js 有这个术语吗@@?)
请问有什麽方法可以存取到这个成员变数吗?谢谢 m(_ _)m
--
雁子回到了遥远的北方 你的名字我已想不起来 别怪我 生命太匆忙
http://blog.xamous.net
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 218.175.81.213