gpt4 book ai didi

Javascript 类在函数内调用函数

转载 作者:行者123 更新时间:2023-11-28 16:17:48 24 4
gpt4 key购买 nike

function ObjectProvider() {
this.url = "ajax/inbounds.php"
this.inBounds = function () {
this.removeMarkers();
var url_string = this.url;
$.getJSON(url_string, function (data) {
for (i = 0; i != data.length; ++i) {
this.createObject(data[i]);
}
});
};
this.createObject = function (_data) {};
this.removeMarkers = function () {};
};

所以这条线

this.createObject( data[i] );

遇到一些问题,但是

this.removeMarkers();

工作正常。

这两个函数都在 ObjectProvider 对象中定义。已尝试添加一个名为 test() 的函数,但不喜欢在 JSON 回调函数中调用任何内容。

最佳答案

这是一个典型的范围界定问题; $.getJSON() 回调函数中的 this 不再是相同的 this

要解决此问题,您必须在调用 $.getJSON() 之前保留对 this 的引用,例如

var self = this;
$.getJSON(url_string, function(data) {
// self.createObject( data[i] );
});

或者,使用 $.proxy 绑定(bind)成功回调函数:

$.getJSON(url_string, $.proxy(function(data) {
this.createObject(data[i]);
}, this));

关于Javascript 类在函数内调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10878020/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com