Javascript/Typescript Issue with Closures - Storing a function of an object as a variable

Struggling with understanding JavaScript/TypeScript closures even after reviewing multiple examples online.

Here's the code causing me issues:

let obj = {
  message: '222',  
  printMessage: function() {
    return this.message
  },
}

console.log(obj.printMessage()); // 222
let func = obj.printMessage;
console.log(func());             // undefined

Encountering the error

Cannot read property 'message' of undefined
when running this code.

Aware that directly calling obj.printMessage() works but looking to return the printMessage function as a variable for use in another function.

Suspecting the issue lies in closure, seeking guidance on tackling it.

Appreciate any insight shared.

===========================================

Update:

Managed to resolve the problem through further code experimentation.

Here's the solution implemented:

let obj = {
  message: '222',  
  printMessage: function() {
    return this.message
  },
  getPrintMessage: function () {
      return () => this.printMessage()
  }
}

console.log(obj.printMessage()); // 222
let func = obj.getPrintMessage();
console.log(func());

Incorporated an additional function to return an anonymous function calling this.printMessage(), enabling access from outside the object.

Grateful for all contributions and support provided.

Answer №1

Step into the fascinating world of utilizing the this keyword in JavaScript.

The inherent value of this is dependent on how a function is invoked (runtime binding). In the particular example provided, this refers to a method within an object lacking a proper reference.

To manage the binding of the this context, one can employ techniques such as using the call or bind methods, or alternatively explore the potential of getters and setters.

let obj = {
  message: '222',
  get mess() {
    return this.message
  }
}

const currentMessage = obj.mess

// Both yield equivalent results

currentMessage
obj.mess

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

Jade will be loaded after Angular finishes loading and resolving all variables

I have an uncomplicated page built with nodejs, utilizing angular on the front end and nodejs on the back end. When I load data in a controller using $http like so - angular.module('student').controller('StudentDashBoardController', f ...

The alpha channel in THREE.js GLTFLoader is not displaying transparency and instead showing a white background

I imported a model created in Blender: https://i.sstatic.net/SF0D2.png The texture of the model is partially transparent, achieved by converting the white background to alpha using nodes: https://i.sstatic.net/lSZ6w.png To make this work correctly, I en ...

Develop a custom JavaScript code block in Selenium WebDriver using Java

Recently, I came across a JavaScript code snippet that I executed in the Chrome console to calculate the sum of values in a specific column of a web table: var iRow = document.getElementById("DataTable").rows.length var sum = 0 var column = 5 for (i=1; i& ...

In PhantomJS, where is the location of the "exports" definition?

Consider the following code snippet from fs.js: exports.write = function (path, content, modeOrOpts) { var opts = modeOrOptsToOpts(modeOrOpts); // ensure we open for writing if ( typeof opts.mode !== 'string' ) { opts.mode = ...

Issue with Browser Geolocation API not throwing errors or properly handling timeouts

For quite some time, I've been mystified by the black magic of geolocation. I'm reaching out to see if any of you can shed some light on this for me. Here's the geolocation function in JS that I've been working with: // User Position ex ...

Keep image height consistent and prevent resizing

I've hit a roadblock while trying to find a solution for this issue. There must be an easy fix that I'm overlooking... The problem arises when viewing the table with flags on a small screen (on mobile) - the image on the left seems to get sligh ...

Can animations be stacked in a queue while using velocity.js?

I'm currently tackling a project involving a push menu. When the content div slides over, the menu buttons come in with a slight animation as they appear on the screen. However, if the user rapidly opens and closes the menu multiple times, the items o ...

Viewing documents stored on the file server using the frontend interface (angular)

I am currently working on an Angular application that interacts with a .NET Core API. I have encountered an issue where the file upload process successfully uploads files to a file server, but I am unable to access these files on the front end. Despite at ...

What steps can I take to set up AJAX-based long-polling in Microsoft Edge?

I have been working on setting up a basic long-polling skeleton that functions across different browsers. While my solution works perfectly in Chrome, I am facing difficulties getting it to work in Edge. Upon loading the page in Edge, there are no visible ...

Creating a mapping strategy from API call to parameters in getStaticPaths

I am attempting to map parameters in Next.js within the context of getStaticPaths, but I am facing issues with it not functioning as expected. The current setup appears to be working without any problems. https://i.stack.imgur.com/LeupH.png The problem a ...

Error message encountered while attempting to search on Wikipedia: "Unable to connect to *ngFor" (Angular2 / HTML / Javascript)

I am currently working on developing a search bar that will search through data and display the results based on the input in the search box after clicking a button. The data can be sourced from Wikipedia or local fake data, it doesn't make a differen ...

FIREBASE - ReferenceError: Authorization cannot be accessed until initialized

Currently, I am in the process of learning about Auth with Firebase using NextJS. I have been trying to grasp the concept by referring to multiple sources such as articles and YouTube videos, but I have encountered an error that is hindering my progress. ...

What is the process for finding GitHub users with a specific string in their name by utilizing the GitHub API

I'm looking to retrieve a list of users whose usernames contain the specific string I provide in my query. The only method I currently know to access user information is through another endpoint provided by the GitHub API, which unfortunately limits t ...

Unable to fetch source for HTML img tag

I am struggling with using jQuery to retrieve the src attribute of an image when it is clicked. Unfortunately, my current code does not output anything to the console and returns undefined when I try to manipulate it in the browser console. I do not have m ...

Improving the Speed of ASP.NET TreeView

How can we optimize performance when using the TreeView component? When I say optimize performance, I am referring to reducing the number of client-server trips, such as postbacks. Does this imply that the majority of the business logic will need to be i ...

The absence of underline in mat-form-field is not displayed

Hello everyone, I'm fairly new to working with Angular and I've been trying to implement expanding sections in my application by following the example provided in this link. However, I'm facing an issue where the underline is not displayed w ...

Having trouble with installing Typescript on a MacBook?

I have been attempting to follow the instructions provided on TypeScriptLang.org but for some reason, I am unable to successfully download typescript. This is what I have tried so far: mkotsollariss-MacBook-Pro:/ mkotsollaris$ which node /usr/local/bin/n ...

Create additional object property and include in current object's properties dynamically

I have a JSON object that looks like this: "highChart":{ "xAxis":{ "categories":[ "SYN 13 ", "Settlement", "Service Interaction", "FNOL", ...

How can I transfer a MongoDB collection to an EJS file in the form of a sorted list?

I have successfully displayed the collection as a json object in its own route, but now I want to show the collection in a list under my index.ejs file (I'm still new to ejs and MongoDB). Below is the code that allows me to view the json object at lo ...

Sending data twice with jQuery AJAX to PHP

I implemented a standard JavaScript countdown timer that triggers an AJAX request to save data in a database once the countdown finishes. However, I've noticed that the entry is being saved twice. Any insights on why this might be happening? var cou ...