Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript: Store a function call in a variable / object

I was wondering if there’s an easy way to define a function call inside an object. I know eval() works for this purpose but I’m trying to avoid it if possible. This is my scenario:

function my_function(val) { console.log("The value is " + val) }
const my_object = {"a": "nothing", "b": 0, "c": my_function("this")}
my_object.c();

What I’d like to happen is when you call my_object.c(), it runs my_function() with the given parameters at that moment. What understandably happens is that c gets its value from the return of the function once when the script starts up.

What works as intended is defining it as "c": function() { my_function("this") } instead: It works but looks really ugly. Is there a simpler way of writing that, to work the same way but include only the name of the function being called?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I think what you’re looking to do is bind.

const my_object = {
  c: my_function.bind(this, 'this'),
};

See also: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading