0

What is the difference in doing this.functionName vs this.functionName()? I don't have a clear understanding between the two.

Siva
  • 1,256
  • 3
  • 13
  • 29

4 Answers4

5

this.functionName reads the value of property functionName of the object this.

this.functionName() reads the value of property functionName of the object this and tries to call it as a function. It will throw an error if the value of this.functionName is not a function.

Decompose the statement as

this.functionName()
\____callee_____/
\_CallExpression__/

"callee" can be any expression but must resolve to a function object.

Check out the AST if you are curious.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
2

When evaluated, the first one is just a reference to the function, in the second case the function gets executed, and the expression will be evaluated to be the return value of the function.

doldt
  • 4,466
  • 3
  • 21
  • 36
1

this.functionName returns the function itself, this.functionName() will execute the function and return the result

function A() { 
    this.doSomething = function() { 
        return "A"; 
    } 

    this.doOtherThing = function() { 
        console.log(this.doSomething); 
        console.log(this.doSomething());         
    }     
}

var a = new A();
a.doOtherThing()

Prints the following to the console:

function () { 
  return "A"; 
}

A

The first is the function itself, the second is the result of the function. There are a number of reasons you may want to return the function without executing it, for example could pass it to another function to be called after an AJAX request completes.

toby
  • 683
  • 2
  • 6
  • 16
1

this.functionName is a reference to the function object.

This can be useful if you want to check for the existence of the function before calling it, e.g.

if (typeof(this.functionname) == 'function') {
    this.functionname();
}

this.functionName() actually invokes the function.

EJK
  • 12,332
  • 3
  • 38
  • 55