How to call the method of a JS object from duktape/C?
See original GitHub issueI thought this should be a simple one but to my surprise I cannot figure out the proper way. Calling a function/method with duktape/C is easy via duk_pcall/duk_pcall_method. The tricky part is how to get to the function to call?
I have a global var process and want to call it’s emit() method. I can simply evaluate the string:
process.emit("exit", code)
and that works nicely. But how to do that in duktape/C? This is what I tried:
duk_get_global_string(ctx, "process");
duk_get_prop_string(ctx, -1, "emit");
duk_push_string(ctx, "exit");
duk_push_int(ctx, exitCode);
duk_int_t r = duk_pcall(ctx, 2);
duk_pop_2(ctx);
but that doesn’t trigger the event and the return value is 1. What’s the correct way?
Issue Analytics
- State:
- Created 6 years ago
- Comments:27 (20 by maintainers)
Top Results From Across the Web
How to make function calls - (o) Duktape Wiki
How to make function calls. API calls for invoking functions are mostly quite straightforward: they are given a target function and a list...
Read more >Javascript: Calling object methods within that object
Well, from your first example: var _obj = { property: value, method1: function() { // do stuff }, method2: function() { // use...
Read more >Working with objects - JavaScript - MDN Web Docs - Mozilla
A property's value can be a function, in which case the property is known as a method. Objects in JavaScript, just as in...
Read more >Object methods, "this" - The Modern JavaScript Tutorial
Then we can call it as user.sayHi() . The user can now speak! A function that is a property of an object is...
Read more >How To Use Object Methods in JavaScript | DigitalOcean
Objects in JavaScript are collections of key/value pairs. The values can consist of properties and methods, and may contain all other ...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found

Maybe it’d be helpful to have a wiki page with a table containing the Duktape API calls and the Ecmascript equivalents. Behavior of the “this” binding is not always well understood because you don’t deal with it as directly in Ecmascript code as you do in the C API.
@svaarala That looks very concise and yet covers all relevant cases. That’s how it should be 😃 The only improvement I’d like to see is code formatting in the table. And maybe a word or 2 about
duk_call_methodvs.duk_call_prop.