What distinguishes a function with a name from one without a name?

Why does a function added to an object through a method have no name (anonymous), while a function written for an object in the code has a name?

let calc = new Calculator;

//console.log( calc.calculate("3 + 7") );

let powerCalc = new Calculator;
powerCalc.addMethod("*", (a, b) => a * b);
powerCalc.addMethod("/", (a, b) => a / b);
powerCalc.addMethod("**", (a, b) => a ** b);


let result = powerCalc.calculate("2 ** 3");
//console.log( result );

console.log(powerCalc.methods["+"].name); // has a name
console.log(powerCalc.methods["*"].name); // has no name

function Calculator () {

  this.methods = {
    "-": (a, b) => a - b,
    "+": (a, b) => a + b,
  };

  this.calculate = (str) => {
    let split = str.split(" "),
        a = Number(split[0]),
        operator = split[1],
        b = Number(split[split.length-1]);

    if (!this.methods[operator] || isNaN(a) || isNaN(b)) return NaN;
    
    return this.methods[operator](a, b);
  }

  this.addMethod = (operator, method) => {
    this.methods[operator] = method;
  }

}

Answer №1

In an object literal, when a property's value is defined as an anonymous function, the function automatically inherits the property name as its own name.

This convention simplifies the process of defining object methods, where the property name serves as the method function's identifier.

However, this automatic assignment doesn't occur if the function is declared outside the object literal and then later assigned to a property. To achieve this behavior manually, you can utilize the addMethod() method:

this.addMethod = (operator, method) => {
    this.methods[operator] = method;
    if (!method.name) {
      method.name = operator;
    }
}

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

Designing a layout with one box on top and two beneath it, covering the entire page, can be achieved by following these steps

https://i.sstatic.net/A1eUh.png I am currently working on a project where I want to divide the screen into three sections. One section will cover half of the screen to display an image slider, and the remaining half will have two sections which is already ...

Exploring variable access in React Native

It is my intention to access different variables using indexing. To begin, I initialized them as follows: const refRBSheet0 = useRef(); const refRBSheet1 = useRef(); const refRBSheet2 = useRef(); const refRBSheet3 = useRef(); const refRBSheet4 ...

Issues with the functionality of apostrophes and commas in an alert box, specifically in a confirmation box

I have been developing a PHP script for managing karaoke events. Once the user submits a search term, the script displays the available songs from the database. The user can then click on a song title to add it to a queue. This "queue" data is stored in a ...

useEffect initiates all actions

I'm currently exploring hooks functionality within a Next.JS project. I've successfully used a useEffect to track scrolling behavior in order to dynamically change the content displayed in a header when the page is scrolled. const [ scrollY, setS ...

Having issues with django-autocomplete-light triggering JavaScript errors

My implementation of django-autocomplete-light is causing some issues with rendering autocomplete options. There is a section on the website where it functions perfectly, but in another section, it only works partially. The autocomplete options display c ...

Is it possible to access the ID element of HTML using a variable in jQuery?

I have fetched some data from a JSON ARRAY. These values include Value1,Value2, and Value3. Additionally, I have an HTML checkbox with an ID matching the values in the array. My goal is to automatically select the checkbox that corresponds to the value re ...

In React Native, changing the translation of an element causes it to shift below all other elements, regardless of

Check out this sandbox project: I'm trying to create a simple animation using translation in React Native, but I'm facing an issue where when I move the element to the right and down, it goes under other elements. However, if I move it left and ...

Creating TypeScript declarations for standard JavaScript functions and objects so they can be accessed in a TypeScript project

In my TS project, I am currently using Node, Express, and Handlebars along with some client-side JS successfully. I don't have any other client-side frameworks like React or Angular integrated at this time. Recently, I have been thinking about conver ...

Troubleshooting issues with applying a class on load using JavaScript

I am new to Javascript and I am trying to add a class to an element when the page loads. Specifically, I want to change the background color of the element as a test. However, I keep running into the error message "Uncaught TypeError: Cannot read property ...

Data cannot be transferred to a child element unless it has been initialized during the definition phase

Passing an array data from parent to child component has brought up some interesting scenarios: parent.component.html: <child-component ... [options]="students" > </child-component> Status I: Setting the array on definition ...

Switch from a class component to a functional component in React JS by clicking a button

I am currently facing an issue with navigating from a React.js class component to a functional component and passing data. Here is the structure I am working with: Class component: export default class Dept extends Component { constructor(props) {}; ...

The challenge with encoding URL in Ajax requests

I am trying to send an encrypted message along with the corresponding key (two-way encryption) to a PHP page for decryption, and then receive the decrypted result in the response. Below is an example of how I am attempting to send the encrypted message us ...

The div layer is positioned above the flash object

I have successfully implemented a method where I position a div over a webpage containing a flash object. This absolutely positioned div has a high z-index and captures click events. The main goal is to trigger the click event on the div when the flash obj ...

Guide to incorporating a component in Vue 2

I recently developed a Vue 2.5.2 application using vue-cli. While attempting to create my first component (<jsontree />), I encountered an issue as it functions independently, but I am struggling to understand how to properly register it for use in ...

Click the div to fold it

I would like the div to fold down when clicked on and then fold back up when clicked again. Here is my jQuery code: $(".fold_reply").click(function() { if ($('.reply').css('display') === 'none') { $(".reply").sh ...

Accessing objects within an array of arrays of objects in react – a guide

First, I executed the following function: const getData = async (array,s,number) => { const response = await axios.get(s); const theData = response.data array[number]=theData } Then, I did this: let array=[] ...

When the toggle enabled div is clicked, the drag event is triggered

My draggable div has a "splitter" for expanding and collapsing, but it should only do so on double click or drag. However, when I single click the splitter while the div is collapsed, it repositions to around 10px width. I've attempted using 'st ...

Synchronizing client information in real-time: tips, tricks, and expert advice

Currently, I am developing a PHP backend and utilizing JS/Jquery for the front end of an application that aims to facilitate near real-time communication among users. My main concern right now is determining the most effective approach to achieve this goal ...

An in-depth guide to accessing saved files using Multer's disk storage feature in Node.js

I have successfully implemented the image storage functionality on my local disk using multer. However, I encountered an error "Cannot GET /uploads/image-1547436792386" when trying to use the GET method. Below is the code from my image-upload.js file: con ...

How can you reach a constant from a different component in React?

I am new to developing a react application and struggling with accessing const data from another component. The specific constant I need access to is located in the TableComponent.js file. TableComponent.js export default function({ infinite }) { const [ ...