Troubleshooting issue with v8 callback failure when interacting with JavaScript objects stored on the heap

Creating an instance of a JavaScript object is easy, for example;

myObj1 = new myObject("Object1");

Next step is to call a node.js c++ addon which triggers a callback to the Javascript object...

myAddon = require('myAddon');
myAddon.greet(myObj1.name);

Here is the c++ callback code snippet:

Local<Function> callback = Local<Function>::Cast(args[0]);
Isolate* isolate = args.GetIsolate();
const int argc = 1;
const char *parm = "Hello";
v8::Local<v8::Value> argv[argc] = {  v8::String::NewFromUtf8(isolate, parm) };
callback->Call(isolate->GetCurrentContext()->Global(), argc, argv);

Encountering a problem where the binding doesn't correctly callback to the specified instance of myObject, but instead seems to go back to the base JavaScript class. Thus, causing a loss of instance data.

After extensive research in the past couple of days, it appears that the first parameter passed to the Call() method serves as the "this" pointer in v8. Could the issue lie in using a Global context?

If anyone has insights on how to accurately callback to a JavaScript object stored on the heap, please share.

Answer №1

When you call a method like a.b.c(d), the function stored at a.b.c is invoked with the value of a.b being assigned to this within that function's context.

This specific behavior only occurs in this scenario.

For instance, when you execute myAddon.greet(myObj1.name), the greet function from the object myAddon is called with this set to myAddon. No other magic happens here. The detail that the function came from myObj1 is not preserved, making it impossible for your C++ code to reference this object!

In JavaScript, the recommended practice is for the callback-passing code to bind this as needed using the bind() method, such as:

myAddon.greet(myObj1.name.bind(myObj1));

Your C++ code will receive a proxy function object since bind() creates a new function. This proxy will invoke myObj1.name with this set to myObj1, relieving your C++ code from handling it.

To demonstrate, the expression myObj1.name.bind(myObj1) is similar to

(function (o, f) {
    return function () { return f.apply(o, arguments); };
}(myObj1, myObj1.name))

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be the reason for encountering a SyntaxError due to an unexpected end of JSON input?

Here is the code snippet that I have developed using express and node.js: const express = require("express"); const https = require("https"); const app = express(); app.get("/", function(req, res) { ...

Optimal management using an image and an onClick event to trigger a JavaScript function

Which control stands out as the optimal choice for displaying images, executing JavaScript functions without postback, and possibly even changing images on hover? ...

Error in content policy for CSS in Stripe Checkout

I am currently attempting to integrate Stripe Checkout into my Ionic App. I have created a Directive that injects the form into my content view, however, upon execution, the CSS fails due to a content policy violation: checkout.js:2Refused to load the s ...

The video.play() function encountered an unhandled rejection with a (notallowederror) on IOS

Using peer.js to stream video on a React app addVideoStream(videoElement: HTMLVideoElement, stream: MediaStream) { videoElement.srcObject = stream videoElement?.addEventListener('loadedmetadata', () => { videoElement.play() ...

Using boost::ptr_unordered_map to store references to immutable objects

I'm struggling to get boost::ptr_unordered_map<uint32_t, const Foo> to function properly - it seems like the implementation is converting things to a void*. Do I have no other choice but to modify my methods that encapsulate access to this data ...

Use the 'url' parameter to pass into the ajax function when using jQuery for online requests

I am working with an ajax code that retrieves data from an XML file locally. <script> function myFunction() { $("#dvContent").append("<ul></ul>"); $.ajax({ type: "GET", url: "test.xml", ...

Creating a nested datatable from a JSON array object response is a valuable skill to have in

My API response is in JSON format with nested arrays. I am trying to parse it into a nested datatable, but I can't seem to get it working. Can someone please point out where I went wrong? The JSON data contains passenger information and each passenger ...

What is the most effective method for managing the onSelect data within the select tag in Angular's reactive form functionality?

Can someone please advise on the best approach to handling this scenario? I have a form with multiple fields, including a select tag. <form [formGroup]="myForm"> <select formControlName="" > <option *ngFor="let c of countries" value ...

A different approach to database monitoring instead of using setInterval() - Meteor.js

To create a scroll-down message feed when the number of records changes or when a new message is inserted into the document, the approach needs to be simple and efficient. Instead of using setInterval to continuously check for database changes, we can con ...

In what way does s% access the title attribute within the Helmet component?

I am seeking clarification on how the reference to %s is connected to the title attribute of the <SEO /> component within the <Helmet /> component in the gatsby starter theme. Can you explain this? Link to GitHub repo On Line 19 of the code: ...

Discovering the content of an internal Database or Table in TYPO3 and showcasing it using JavaScript, JQuery, or AJAX

As a newcomer to TYPO3, I must admit that it's quite intricate, but I'm making progress. All I'm looking for is a simple method to extract content from an internal TYPO3 Database Table that I've set up and send it over to JavaScript/JQ ...

Styling a Pie or Doughnut Chart with CSS

I am working on creating a doughnut chart with rounded segments using Recharts, and I want it to end up looking similar to this: Although I have come close to achieving the desired result, I am encountering some issues: Firstly, the first segment is over ...

Issue with Electron: parent window not being recognized in dialog.showMessageBox() causing modal functionality to fail

Struggling with the basics of Electron, I can't seem to make a dialog box modal no matter what technique I try. Every attempt I make ends in failure - either the dialog box isn't modal, or it's totally empty (...and still not modal). const ...

What is the best way to include the application version in an Electron project using JavaScript

While attempting to publish an update for my app, I encountered a strange error. Can anyone pinpoint the issue? (Note: Node.js is included) Error Message: Unexpected token < <script> console.log(process); let output = <h2 class="page- ...

What is the best way to fetch the class name of an element in JSDOM?

In my current project, I am facing a challenge with extracting the className of an element using JSDOM. Despite being able to locate the element successfully, I have been unable to find any relevant examples or documentation on how to retrieve the classN ...

String validation using regular expressions

Below is the code I am using to validate a string using regular expressions (RegEx): if(!this.validate(this.form.get('Id').value)) { this.showErrorStatus('Enter valid ID'); return; } validate(id) { var patt = new RegExp("^[a-zA- ...

Implementing image-based autocomplete in a search bar within an MVC framework

Seeking assistance to implement a unique feature for my MVC application. I aim to create a search box that suggests images based on user input rather than text. The functionality involves matching the user's input with the "Title" property in an Ent ...

Leverage the power of regular expressions in JavaScript for organizing and handling source files

Embarking on my coding journey with JavaScript, I have also been exploring the world of Three.js, a webgl library. After watching tutorials and conducting experiments, I am proud to share my latest creation: . In my code, you'll notice that the obje ...

Unable to invoke an exported virtual function

I am working with a MyApi.dll which contains an exported class Base with a pure virtual function. Additionally, there is a derived class within the same dll that provides an implementation for the virtual function. A factory function is used to return an o ...

Creating a dynamic way to include usernames in the chatbuilder application without relying on hardcoded

As a newcomer to this site and coding, I must apologize in advance if the answer to my question is too simple. However, I am in desperate need of some assistance. I created a "chatbuilder" as part of my interview process for a development bootcamp. Unfort ...