Good day.

There is a link to some function callBack , located in an unknown object. Is it possible to get an object or its name, in which our function is located?

    1 answer 1

    In this case

      var callback = object.func; 

    When a link to a function is passed and possible objects are known, you can:

     var objects = [ {id: 1, func: function(){return 3;}}, {id: 2, func: function(){return 2;}}, {id: 3, func: function(){return 1;}} ]; var func = objects[1].func; for(var i=objects.length;i--;){ var obj = objects[i]; for(var prop in obj){ if(obj[prop] == func){ console.log(obj); // {id: 2, func: function(){return 2;}} } } } 

    UPD:

    Another option is to store the link to the object itself in all methods of objects that are intended for use as a callback:

     var obj = {possibleCallback: function(){...}}; obj.possibleCallback.root = obj; 
    • Those. Do you offer all objects to be added to a certain array and then compare their function line by line? - Anton Mukhin
    • Another option is to store the link to the object itself in all methods of objects that are intended for use as a callback: var obj = {possibleCallback: function () {...}}; obj.possibleCallback.root = obj; - Specter
    • >> obj.possibleCallback.root = obj; >> And this is possible. Maybe obj.possibleCallback.prototype.root = function () ... Or does JS allow such constructs? - Anton Mukhin
    • Any function is just an object, therefore you can dynamically add this or that property, if you add this property to the prototype, it will be used for objects affected by this function as a designer - Specter
    • A good way to solve the problem. Thank. - Anton Mukhin