Is it possible to use template literals for dynamically naming functions?
let variable = "something"
function `constant${variable}` () {
//perform a task
}
Is it possible to use template literals for dynamically naming functions?
let variable = "something"
function `constant${variable}` () {
//perform a task
}
To define a variable and access its context, you can utilize the this
keyword when declaring your function.
For instance:
let newFunction = "AwesomeDynamicFunction";
this[`${newFunction}`] = () => {
console.log("I'm an awesome dynamic function")
}
Then, you can invoke it by using:
AwesomeDynamicFunction()
To achieve the desired result, you need to make some adjustments to your original code since it won't work as expected due to trying to input a string where a variable name is required.
Additionally, by using 'this' instead of 'window' or 'global', you can utilize the code snippet in both browser and node.js environments.
let variable = "something"
this[`constant${variable}`] = () => {
console.log("it works");
}
constantsomething()
To create a dynamic function using template literal, you have two options. One way is to utilize the window object like this:
let variable = "example"
window[`dynamic${variable}`] = function () {
console.log('creating dynamic function')
}
Alternatively, you can use a separate object approach:
let variable = "example"
var obj = {
[`dynamic${variable}`]: function () {
console.log('creating dynamic function')
}
}
obj.dynamicexample()
It's not possible like that, as a template literal is always resolved to a string and you cannot define a function "abc"() { ... }
.
Nevertheless, you can attempt to place it in the global scope by using the name followed by bracket notation. For instance, if running in a browser:
let variable = "something"
window[`constant${variable}`] = function() {
console.log("Hello!");
}
constantsomething();
In a Node.js project, the approach might look something like this:
let variable = "something"
global[`constant${variable}`] = function() {
console.log("Hello!");
}
constantsomething();
When setting up Firebase Auth in my expo app (using Google Auth), I needed to store my firebase variables in a .env file containing API_KEYS, AuthDomain, and more. To access these environment variables, I utilized expo constants in my firebase.ts file. Ini ...
Currently, I am in the process of learning automation testing for an AngularJS application. However, I have encountered an "object expected" error on line 4, which is pointing to the first line of my script. describe("Homepage", function() { it("Navig ...
Here is the code for a bootstrap table: <body leftmargin="0" topmargin="0" bgcolor="#ffffff" marginheight="0" marginwidth="0"> <div class="container-fluid h-100"> <div class="row float-right align-items-center" style="height: 5%;"> ...
When trying to toggle the visibility of my TextBox based on a selected value in a RadiobuttonList, I initially wrote the following code: $("#<%= rbtnIsPFEnabled.ClientID %>").click(function () { pfno = $("#<%= txtPFNo.ClientID %&g ...
Having mastered Apollo and GraphQL with the help of Odyssey, I am currently engrossed in creating my own project using Next.js. This involves fetching data from not one, but two different GraphQL endpoints. The dilemma at hand: How can I efficiently retri ...
I am currently working on customizing notifications that appear when a Symfony entity is successfully updated. What I have implemented so far can be found here : var messagesTypes = { "notice": ["This is a green NOTICE"], "error": ["This is a red E ...
I am currently in the process of integrating an Angular app into an existing jQuery application. Let's say I have a basic button in my HTML code. My goal is to load the Angular app and execute controller code when the button is clicked. To achieve t ...
Given the string testserver\sho007, how can I utilize jQuery to extract only the value sho007? ...
function addEventListenerToElement(element, event, handlerFunction) { if(element.addEventListener) { element.addEventListener(event, function(){ handlerFunction(this.getAttribute("src")); }, false); } } //initialize the function addEve ...
I am currently attempting to present JSON data in a tabular format on a website. The raw data retrieved from the API endpoint appears as follows: {"body":"[{\"id\":\"67341472528\",\"name&bso ...
Can you assist me in recreating my idea from an image? I am having trouble understanding how to select and place other elements, and then return them to their original positions after deselecting... I attempted to use a grid but it did not work properly. ...
I've been working on a React.js project that integrates with Firestore, and I ran into an issue where using the get method for fetching documents resulted in a "Can't perform a React state update on an unmounted component" warning. However, when ...
Primarily, the challenge I'm facing is unique from what I have come across in my research on "google". My setup involves using Spring Boot as a signaling server to establish connections between two different tabs of the browser or utilizing two peerCo ...
I'm having trouble comparing the result of an ajax call with a string. The ajax call is returning the correct result, but I'm struggling to get the if statement to properly compare it with my string. Any suggestions on how to approach this? ...
I am facing an issue with the code below; function add_js_functions(){ $gpls_woo_rfq_cart = gpls_woo_rfq_get_item(gpls_woo_rfq_cart_tran_key() . '_' . 'gpls_woo_rfq_cart'); if(is_array($gpls_woo_rfq_cart)){ $count = count($gpls_woo_r ...
Many generators I've come across create a squared matrix, assuming the output length based on the number of items provided. However, I'm looking for a solution where I can specify both the items and the desired length. It seems like such a simpl ...
Interested in developing a web application using Node.js that allows users to log in (authentication). The app will have 3 non-secure pages (/home, /contact, /about) and one secure page (/admin). I've been consulting the Mean Machine book from scotch. ...
I'm making a post request and receiving the response as follows: " [Symbol(Response internals)]: {url: 'https://login.somenewloginpage'}" My intention is to open a new page using that URL, but unfortunately it does not redirect t ...
Is it possible to modify this function so that when the currency is not USD, the $ sign is not added in front of the amount? var convertToCurrency = number => { if (!number) return ''; return new Intl.NumberFormat('en', { ...
**import { controls } from "../../../constants/controls"; import { useKeyPress } from "../../../hooks/useKeyPress"; import { useArena } from "./useArena"; const getDamage = (attacker, defender) => { let damage = attacker ...