I don't like getJSON
for this very reason, it's too limited compare to ajax
.
Basically, when the success
function is executed, this
is not pointing anymore to your ObjectProvider
instance. To solve that, you can use ajax instead, that provide an useful context
property:
function ObjectProvider(){
this.url = "ajax/inbounds.php"
this.inBounds = function(){
this.removeMarkers();
var url_string = this.url;
$.ajax({
url: this.url,
dataType: "json",
context: this,
success: function(data) {
for( i=0; i != data.length; ++i ){
this.createObject( data[i] );
}
});
};
this.createObject = function(_data){};
this.removeMarkers = function(){};
};
Otherwise you could use bind:
$.getJSON(url_string, function(data) {
for( i=0; i != data.length; ++i ){
this.createObject( data[i] );
}
}.bind(this));
In order to create a new function "bound" to a specific context object, but only in the browsers that are supporting ES5 or have a shim for that (as the link above describe).
There is also the version mentioned, the closure to store the instance, but I personally prefer avoid that when is not strictly necessary. Nowadays, for this kind of behavior, it's considered an old practice.
And talking about closure: you don't need to declare the function inside the constructor. In that way they're added dynamically all the times, and if they're not accessing to some inner variables there is no reason, it's just a waste of resource. To be clear, in your case, if you have:
var a = new ObjectProvider();
var b = new ObjectProvider();
console.log(a.createObject === b.createObject) // false
A better approach could be:
function ObjectProvider() {
}
ObjectProvider.prototype = {
constructor: ObjectProvider,
url: "ajax/inbounds.php",
inBounds: function () { /* ... */ },
createObject: function () { /* ... */ },
removeMarkers: function () { /* ... */ }
}
var a = new ObjectProvider();
var b = new ObjectProvider();
console.log(a.createObject === b.createObject) // true
But at that point, if you don't have any dynamic property (e.g. the URL is always the same, is not passed to the constructor as parameter) maybe you don't have the need to have different instances as well, and you can just and up with:
var ObjectProvider = {
url: "ajax/inbounds.php",
inBounds: function () { /* ... */ },
createObject: function () { /* ... */ },
removeMarkers: function () { /* ... */ }
};
And use it as "singleton":
ObjectProvider.createObject()