JavaScript Object Destructuring  and the lost Context

JavaScript Object Destructuring and the lost Context

I recently came across this issue in the NodeJs repository on GitHub, the issue (https://github.com/nodejs/node/pull/53934) was caused by 2 different problems, one of them was caused by the destructuring of an object. Here is a summary of the issue by the author:


The first issue was the crash with the error message: ERROR: v8::Object::GetCreationContextChecked No creation context available. This error was caused by lib/internal/fs/read/context.js. We were destructuring the result of internalBinding('fs') which caused the creation context of the function being unavailable.
Previously, it was:
const { close } = internalBinding("fs");

close(fd, req);        
The fix was:
const binding = internalBinding("fs");

binding.close(fd, req);        

Its important to note that the destructuring of an object can cause the object's orignal context to be lost, this can be a problem when you are trying to access the object context in a function. Here is an example of how this can happen:

const obj = {

  firstname: "John",

  lastname: "Doe",

  fullname: function ()  {
    return `${this.firstname} ${this.lastname}`;
  },

};

// Output: John Doe

console.log(obj.fullname());

// destructuring the object

const { fullname } = obj;

// Output:  undefined undefined

console.log(fullname());        

In the example above, the fullname function is destructured from the obj object, when the function is called, the this keyword is no longer referencing the original obj object, this is because the fullname function is plucked out of the obj and is no longer part of its context

so be careful when destructuring objects in JavaScript mainly functions as it can cause the object's context to be lost and can lead to unexpected behaviour.


To view or add a comment, sign in

More articles by Parvesh M.

Explore content categories