function modifyDatabase(tabla, id, objData, callback, arrayCallback){
$.ajax({
url: 'modifyDatabase.php',
type: "POST",
dataType: "json",
data: 'tabla='+tabla+'&id='+id+strData,
success: function(data){
callback(data);
},
});
}
var obj = {
set: function (data){
alert(this.var1);
},
var1: 100
}
function modifyDatabase('', '', '', obj.set, '');
When running this, I get an error message telling me that this.var1 is not set or undefined. If I call the method from somewhere else (not from an asynchronic response) it works fine.
Seems as if the method ‘set’ is not inside ‘obj’.
What is going on?
,
When you pass a reference to a function this way, it’s actually not passing a reference to the object as well. A quick fix is to create an anonymous function that references the actual object via closures. Here’s a good description of why it didn’t work: http://bitstructures.com/2007/11/javascript-method-callbacks
In short, you need to do:
function modifyDatabase('', '', '', function(){obj.set();}, '');