1

I need to store a function alongside with its parameters on an object, that is to say something like this:

function myFunction(params) {
   console.log('Params',params);
}

const obj = {method: myFunction, params: [params]};

how can I construct this function and its parameters again in order to execute it from what I have in obj?

2
  • Note that the ) (closing parenthesis) just before the ; at the end of const obj = {method: myFunction, params: [params]); should be a } (closing curly brace). Commented Aug 18, 2020 at 15:51
  • What do you mean by "construct"? Commented Aug 18, 2020 at 15:51

3 Answers 3

2

I'm not sure what you mean by "construct," but you can call it like this:

obj.method(obj.params);

Live Example:

function myFunction(params) {
   console.log('Params',params);
}

const obj = {method: myFunction, params: ["example"]};
// Note: Fixed typo −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^

obj.method(obj.params); // Shows: Params example

Sign up to request clarification or add additional context in comments.

1 Comment

Oh, that was quick answer... I had something like this, but it was failing... thank you, this solves my problem.
1

more beautiful but requires ES6

const  myFunction = (params)  => {
   console.log('Params',params);
}

Now you can put it in your object how you did. you can execute it by using

obj.method(obj.params)

Comments

1

How about using a closure to store the params and then returning another function? Then you wouold not have to store them within an object, like so:

function createClosure(params) {
  return function {
    console.log(`Params: ${params}`);
  }
}

or in ES6 Syntax:

const createClosure = (params) => () => {
  console.log(`Params: ${params}`);
};

In both cases, you could store and call the function like this:

const myClosure = createClosure(params);

// then somewhere else
myClosure(); // prints params

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.