Bagong21
Bagong21

Reputation: 497

What do the parentheses mean when you're declaring/calling a property?

Example 1:

function a(){
  return "ok";
}

function b(){
  this.c = a;
}

var d = new b();
alert(d.c()); // Result "ok".

Example 2:

function b(){
    this.c = a();
}

var d = new b();
alert(d.c); // Result "ok".

What do the parentheses mean in this case?

Upvotes: 0

Views: 176

Answers (4)

Sony Santos
Sony Santos

Reputation: 5545

Although there's enough right answers here, I'll show an interesting consequence:

var counter = 1

function a() {
  return counter++
}

function b() {
  this.c = a;    // your example 1
  this.e = a();  // your example 2
}

var d = new b();

//a() was evaluated once, result put in e
alert(d.e);         // 1
alert(d.e);         // 1
alert(d.e);         // 1

//a() is evaluated each call:
alert(d.c());       // 2
alert(d.c());       // 3
alert(d.c());       // 4

Upvotes: 0

Cameron
Cameron

Reputation: 98746

First case:

this.c=a;

This sets the c property of the object (that b is called on) to a reference to the function a.

Any function can be called (even via a reference) using the () syntax, which is what alert(d.c()) does.

Second case:

this.c=a();

This calls a, and sets c to the result (i.e. return value) of a, which is the string "ok".

Then, retrieving the value of c with alert(d.c) will yield the same result as your first example, but it is arrived at in fundamentally different ways.

One way stores a reference to the function itself, and calls it when its value is needed, while the other calls the function right away and stores only the result for later retrieval.

Upvotes: 1

avpaderno
avpaderno

Reputation: 29679

In the first case, with this.c = a you are setting this.c with the "pointer" to a function, which you then call with d.c().

Upvotes: 0

David Tang
David Tang

Reputation: 93674

Putting () after a function calls it - causing the function to be executed. In your examples, the function is a.

Your two cases can be thought of as:

Example 1

d.c = a;
d.c(); // Call function a

Example 2

d.c = a(); // Call function a, put result in d.c
d.c;

In either case the function a is being called with () exactly once - hence they produce the same output.

Upvotes: 3

Related Questions