The situation is this: I want to use a single duktape/C function for all functions I define on my objects + prototypes. For that I have a function map which takes a function name and a callback (a std::function
actually) and can so easily do some common processing and have simpler callbacks (can even use in-place lambdas for that).
That already works nicely, with one problem: same named functions on different objects. In order to disambiguate I now use the heap pointer of an object (or a prototype, which is also an object) as further qualifier. Hence when my central duktape/C function is called I first look if the function is global (i.e. is a defined on the global object). If that fails I get the this
binding and do a lookup with its heap pointer. If that also fails I walk the prototype chain and see if I can find the function on one of the prototypes.
This works well to 99%, except in cases where I don't have a this
binding (or a wrong one, like for Function.prototype.apply()
).
My question is therefor: how can I get the original prototype for a function in my central duktape/C callback?
The answer is simpler than I first thought. For that central function map you need to have the function name. That has to be set as property on the function object you create when you define a new function on an object or prototype.
The same approach can be used for the original object/prototype. Simply add a back reference to that to your function object as another property (say "ptr"). With that you can easily get not only the function's name but also the context for it's execution. And no walk of the inheritance chain is necessary since we already have the correct object/prototype.