access this on external callback

心不动则不痛 提交于 2020-01-05 04:05:46

问题


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)
}


来源:https://stackoverflow.com/questions/38439132/access-this-on-external-callback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!