-5

Why is assigning method to object property not supported on that way:

neki1: pisaniMethod() 

It seems like when assigning method to object property is not supported with brackets?

function pisaniMethod(){return 'testing';}

var person = {        
    neki: pisaniMethod, //this works
    neki1: pisaniMethod()  //this is not working
};

I guess I was wrong with this:

person.neki1();

I've tried to make a function call on neki1.

FrenkyB
  • 6,625
  • 14
  • 67
  • 114
  • 2
    `pisaniMethod()` is a function call.. `neki1` will have `testing`.. – Suraj Rao Apr 15 '17 at 07:39
  • 3
    What does *work* mean for you? It does assign result of function call to the `neki1`. So, that is wrong? – buræquete Apr 15 '17 at 07:40
  • 1
    Putting `()` after the method name basically says: execute this method *now*! So, in your case value returned by the method will be assigned to `neki1`, while the link to execute the function will be attached to `neki`. – SimpleBeat Apr 15 '17 at 07:42
  • Possible duplicate of [What is the difference between a function call and function reference?](http://stackoverflow.com/questions/15886272/what-is-the-difference-between-a-function-call-and-function-reference) – JJJ Apr 15 '17 at 07:43
  • `neki1` is not a function. You can't call it – Pavlo Zhukov Apr 15 '17 at 07:45
  • 1
    If result of call `pisaniMethod()` will be function you'll be able to call it. But than in `neki` you'll get function that will return function to call – Pavlo Zhukov Apr 15 '17 at 07:50

2 Answers2

3

Because when your assign pisaniMethod you assign link to function. In this way pisaniMethod() you assign result of function call: "testing" in your case.

function pisaniMethod(){return 'testing';};

var person = {        
    neki: pisaniMethod, //this works
    neki1: pisaniMethod()  //this is not working
};

alert(person.neki);
alert(person.neki1);
alert(typeof person.neki);
alert(typeof person.neki1);
Pavlo Zhukov
  • 3,007
  • 3
  • 26
  • 43
1
function pisaniMethod(){return 'testing';};

var person = {        
    neki: pisaniMethod, //this works
    neki1: pisaniMethod()  //this is not working
};

In the first case you are assigning the method. In the second case you are assigning the result retuned by the function since pisaniMethod() is a function call, in your case it will be testing.

Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400