嘗試這代替:
this.update = function (id, size, wall, init) {
$.get(url, "cpart=" + id + "&ref=" + size, (function (self, wall, size, init) {
return function (data) {
if (data) {
var response = JSON.parse(data);
size = response["psize"];
wall.append(response["msg"]);
wall.scrollTop($(document).height());
}
init.apply(self);
}
})(this, wall, size, init));
}
既然你沒有真正指定激活對象,什麼都可能會發生在調用init。
更新: 現在我有更多的關注閱讀你的代碼。
雖然,我並不完全確定你想達到什麼樣的,這裏有一個修訂版:
this.update = function() {
var self = this;
$.get(url, "cpart=" + id + "&ref=" + size, function(data) {
if (data) {
var response = JSON.parse(data);
self.size = response["psize"];
self.wall.append(response["msg"]);
self.wall.scrollTop($(document).height());
}
init.call(self);
});
}
請注意,我不再傳遞參數給update
,而是我直接使用對象的屬性。我在self
變量中保留了一個對象的引用,這個變量可以從我們給$.get()
的匿名函數訪問,因爲它是在圍繞它的函數中聲明的(即「更新」函數)。
更新2
你調用初始化,要求更新,這將導致在初始化再次呼籲!你不覺得應該有辦法打破這個循環嗎?
你會錘擊服務器和用戶的瀏覽器。
我認爲這是最好的,如果你只是告訴我們你想達到什麼目的。
更新3
感覺就像我做你的工作你:J-
// If you're writing a "class", there's got
// to be a constructor somewhere:
function YourClass(id, ref, element) {
// These need to come from somewhere...
this.id = id;
this.ref = ref;
this.element = element;
}
// Now we set your "class methods" on YourClass.prototype,
// so they can be shared among all the instances of YourClass.
// Create instances like this:
// obj = new YourClass();
YourClass.prototype.init = function() {
// You want to give these properties
// alternate names, I'll respect that.
// (notice obj.ref won't ever be updated, but obj.size will)
this.size = this.ref;
this.wall = this.element;
this.update();
}
YourClass.prototype.updateFromData = function(data) {
// I moved this code to a helper "class method" to make things more clear
if (data) {
var response = JSON.parse(data);
this.size = response["psize"];
this.wall.append(response["msg"]);
obj.wall.scrollTop($(document).height());
}
this.init();
}
YourClass.prototype.update = function() {
// Not the most elegant way of coding this,
// but it should be easier to read.
function createUpdater(obj){
return function(data){
obj.updateFromData(data);
}
}
$.get(url, "cpart=" + this.id + "&ref=" + this.size, createUpdater(this));
}
// An alternative to the above would simply be this:
// YourClass.prototype.update = function() {
// $.get(url, "cpart=" + this.id + "&ref=" + this.size, this.updateFromData.bind(this));
// }
有在更新功能沒有參數的 「URL」?這是全球性宣佈的嗎? –
是的,它是全局聲明的 – CBaker
這不是一個很好的使用匿名函數和自我調用函數。你讓它過於複雜 – Ibu