-1

Can I call a function like this in an object? I tried something like this and it seems to be not working. I see that I can put the function in the object. I am more interested to tell which function should be called.

   

function runFunc() {
  console.log("hello");
}
obj = { func: runFunc() };

obj.func;
prabhat gundepalli
  • 907
  • 3
  • 15
  • 39
Allan
  • 92
  • 7

1 Answers1

1

Yes, but your syntax is a bit off. When you create a property that is assigned to the function, you don't add () because that will invoke the function.

Later, when you are ready to invoke the function stored in the property, you do use () to can call the function as a "method" of the object.

The main point being that in JavaScript, we can refer to functions by just saying their name and we can invoke functions by saying their name followed by parenthesis.

function runFunc(){
  console.log("hello");
}

// Create new object and assign the function to a property
obj= { func: runFunc };  // <-- No parenthesis after function name here

obj.func(); // Call function as a "method" of the object

// Or, combine the above and create the property and assign the function at once
// Notice here that the function is anonymous. Adding a name to it won't throw
// an error, but the name is useless since it will be stored under the name of 
// the object property anyway.
obj.otherFunc = function(){ console.log("Hello from other function! ") };

obj.otherFunc(); // <-- Here, we use parenthesis because we want to call the function
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
  • I think I have solved it. var a=function runFunc(){console.log("Hello")};obj={func:a}obj.a(); – Allan Sep 10 '18 at 19:25
  • 1
    @user1894606 You wouldn't name the function (runFunc) when assigning it to `a`. You would just assign an anonymous function to `a` in that scenario. – Scott Marcus Sep 10 '18 at 19:29
  • @user1894606 I have updated the answer to be more closely matched to the pattern you are using and added some more explanation. – Scott Marcus Sep 10 '18 at 19:42