access this on external callback

2019-07-27 18:00发布

问题:

I am working with a library that has custom callbacks.

var dataTable = $("table").DataTable({
    //...

    initComplete: function(settings, json){
        console.log(this);
    }
}

I am trying to externalize this initComplete callback. I defined a custom function:

var initCallback = function(settings, json){
    console.log(this);
}

var dataTable = $("table").DataTable({      
    initComplete: initCallback
}

It does work, but this does not point to the datatable itself. Is there a way to bind this to initCallback so I can access it?

回答1:

What if you passed "this" into your external function?

var initCallback = function(dataTableInstance, settings, json){
    console.log(dataTableInstance);
}

var dataTable = $("table").DataTable({      
    initComplete: function(settings, json) { initCallback(this, settings, json);}
}


回答2:

What you are looking for is the bind function, here is some info.

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

Basically, you can do some like this:

var initCallback = function(settings, json){
    console.log(this);
}

var dataTable = $("table").DataTable({      
    initComplete: initCallback.bind(dataTable)
}