尝试这代替:
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