试试这个:
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
您正在调用 init,它调用 update,这将导致 init 再次被调用!你不认为应该有办法打破这个循环吗?
您将同时敲击服务器和用户的浏览器。
我认为如果你只是告诉我们你想要达到的目标是最好的。
更新 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));
// }