Understanding the problem of scope within a JavaScript object literal

Just diving into the world of programming and joining this community for the first time. I'm currently grappling with a scope issue involving object literals in my code. Any assistance would be greatly appreciated!

var obj = {
   value: 3,
   print:()=>console.log(value)
}

obj.print();

I've noticed that it works fine when using non-arrow functions, but unfortunately I am restricted to using arrow functions in this scenario.

Answer №1

If you want to access the object, you have two options: either use the keyword this within a regular function, or reference the object directly in an arrow function.

const person = {
  age: 25,
  displayAge() {
    console.log(this.age)
  },
};

person.displayAge();

The second option is to reference the object by name (though it's recommended to use the first approach).

const person = {
  age: 25,
  showAge: () => console.log(person.age),
};

person.showAge();

Answer №2

If you're looking to solely utilize arrow functions, one approach is to reference the object within the function like so:

const data = {
   number: 7,
   display: ()=>console.log(data.number)
}

data.display();

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

Determine the number of centimeters on the page as you scroll with jQuery

While searching for plugins that count up and down, I came across many. However, I am looking for something more unique: Imagine having an HTML page that is 70,000cm high. Now picture a counter in one corner that displays the height you are currently at a ...

Any plans for overseeing a Javascript project?

Currently working on developing a game using HTML5 and JavaScript. Are there any tools available for managing revisions and creating a changelog? If not, how do you typically handle project management for your games? ...

Tips for designing a hyperlink insertion modal while preserving text selection

I am working on a React website that utilizes Slate-React () for creating a rich text input field. Currently, Slate uses the browser's prompt() function to add hyperlinks to selected text. However, I need to customize the styling of the prompt modal a ...

Save a value outside of a code snippet

In my Play Framework project, I am working with a views .html file where I have the following code snippet: <script type="text/javascript"> setInterval(function() { $.get("file2", function(${list1}, ${list2}, ${list3}){ $("#result").h ...

Creating arrays of form input elements using Mootools

I searched extensively for a solution to this query, but unfortunately, I could not find the exact answer I was seeking. I am wondering how to access a form input element in mootools that has an array name. I want to use the "double dollar" ($$) function t ...

Learn the process of updating a specific section of a Facebook share link using AJAX dynamically

Here's an interesting scenario I'm dealing with. I'm trying to create a modification to the Facebook share button link where a portion of the link is replaced by a user ID number. This way, when someone clicks on the shared link, it will dir ...

Empty initial value of a number type input element in React using TSX

In the process of developing a react POS app using Typescript, I encountered an issue with calculating change when entering the amount of money received from a buyer. The problem arises when the first value passed to the change calculation logic is empty, ...

AngularJS encountered an error following a successful GET request

I'm attempting to retrieve data from the server using this code snippet. $scope.get_file_list = function() { delete $http.defaults.headers.common['X-Requested-With']; //We don't want OPTIONS but GET request $htt ...

Choosing a String and Performing a Double Click in Selenium with Java

My textbox is disabled, and it includes the following attributes: <div id="writingactivityId2" class="boxSize ng-pristine ng-untouched ng-valid ng-valid-required redactor_editor writingActivityDisabled" ng-focus="editing()" redactor="" readonly="" ng- ...

What is the best way to link a variable to a specific property within a

I am facing an issue with adding data from the server to a JSON property and displaying it. I know that JSON only accepts primitive types, so how can I dynamically add data to a JSON property? For instance, in the code snippet below, I am trying to assign ...

Managing Emails with Vue and Firestore

I am facing an issue with updating the 'email' field. Whenever I try to change the email address, it gets updated correctly. However, when I attempt to log in again, the new email address does not work; only the old one seems to be functional. Ho ...

I am unable to display the answer buttons and organize them accordingly within my project

I'm currently working on a quiz project where I fetch an API containing quiz questions and answers. The API provides an array of wrong answers (3) along with one correct answer. My goal is to display these options as buttons, so I decided to push the ...

What is the method for incorporating a countup feature to figures?

My question is, how can I incorporate a countup animation for the following data: Tested positive cases, Population, Deaths, Percentage of deaths among positive cases, and Last date updated? I find it challenging due to the dynamic nature of these numbers ...

What is the most effective approach to updating data in MongoDB using an array of JSON objects?

My JSON file contains the following data: [ {"person_id": "3455666", "person_app": "bjjiu877y"}, {"person_id": "5633444", "person_app": "rh5556ggg"}, {"person_id& ...

Issue: Inadequate parameters have been supplied for the localized pathname (getPathname()). This problem arose after the inclusion of "next-intl/routing" module

After implementing the config file and replacing : Navigation File import { createLocalizedPathnamesNavigation, Pathnames } from 'next-intl/navigation'; With : Config File import {Pathnames, LocalePrefix} from 'next-intl/routing';} ...

Mastering the art of customizing classes and styles in material-ui (React)

I am facing a challenge with version 1.2.1 of material-ui. My goal is to make the AppBar component transparent by overriding its styles as per the documentation here. This is the code snippet I have been working on: import React, { Component } from ' ...

The malfunction of Bootstrap modal in iterative scenarios

I am currently developing a comprehensive method for handling AJAX requests in my JavaScript code, but I am facing some issues with the Bootstrap modal not functioning as intended. Here is the HTML structure: <div class="modal fade" id="consult_modal_ ...

Retrieving the component's values when utilizing the `<ng-content>` directive

Seeking a technique for accessing the values of a component when utilizing <ng-content>: import {Component} from '@angular/core'; @Component({ selector: 'home-page', template: `<person-box>{{name}}</person-box> & ...

Adding JSON data to a table with the keys in the first row is a simple process that can be achieved

Previously, I have created tables with XML formatted results and JSON data in the "key: data" format. To access the data, I would use syntax like results.heading1 and then map the data into a table by matching the key with the data. Now, a new client is o ...

Child class component unable to access React context value

Having some trouble with accessing a React context value in Employee.js that was set in App.js. It's not rendering correctly and I'm new to React. Any help would be appreciated. Thank you in advance. //index.js export const employeeContext = Rea ...