A method destructured from an object loses its original context

My first of (hopefully) many stories where I expose how little I know about coding and share the lessons I learned (or re-learned).

--

Programmers in 1960s writing software to fly rocket to the moon, versus programmers in 2020s struggling with VIM text editor.
Image source: Programmer Humor

When defining a method on an object, we presumably want this to refer to the object on which the method is defined.

const someObj = {
someProp: 'someValue',
someMethod: function() {
console.log(this.someProp);
}
};
someObj.someMethod(); // will log 'someValue'

Since all the cool kids do it, I use destructuring assignments all over the place. However, destructuring a method from an object causes it to lose its original context. In other words, when invoking a destructured method, this no longer points to the object on which the method is defined.

const someObj = {
someProp: 'someValue',
someMethod: function() {
console.log(this.someProp);
}
};
const { someMethod } = someObj;someMethod(); // will log 'undefined'

Similarly, assigning a method defined on an object to a new variable, and invoking that new function variable causes it to lose its original context as well. In fact, Babel transpiles the code snippet above into the code snippet below to support the one and only browser that doesn’t support destructuring assignments.

const someObj = {
someProp: 'someValue',
someMethod: function() {
console.log(this.someProp);
}
};
const someFunction = someObj.someMethod;someFunction(); // will log 'undefined'

Today I (re)learned.

πŸ“« Hit me up on LinkedIn or email!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Suhan πŸŽƒ Wijaya
Suhan πŸŽƒ Wijaya

Written by Suhan πŸŽƒ Wijaya

I write the legacy code of tomorrow, today. Let’s connect on linkedin.com/in/suhanwijaya

No responses yet

Write a response