javascript – Problem when calling object’s method from ajax.success in jQuery – Education Career Blog

function modifyDatabase(tabla, id, objData, callback, arrayCallback){
        url: 'modifyDatabase.php',
        type: "POST",
        dataType: "json",
        data: 'tabla='+tabla+'&id='+id+strData,
        success: function(data){            

var obj = {
    set: function (data){
    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:

In short, you need to do:

function modifyDatabase('', '', '', function(){obj.set();}, '');

Leave a Comment