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?
>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