1

I don't understand why are there no () after changeName on this line this.chngName = changeName; . My logic is that this.chngName gets assigned to a function return and the functions have a () at the end. Thanks for answering.

function person(firstname, lastname, age, eyecolor) {
    this.firstname = firstname;
    this.lastname = lastname;
    this.age = age;
    this.eyecolor = eyecolor;

    this.chngName = changeName;

    function changeName(name) {
        this.lastname = name;
    }
}

myMother = new person("Sally", "Rally", 48, "green");
myMother.chngName("Doe");
document.write(myMother.lastname);
Dave Newton
  • 152,765
  • 23
  • 240
  • 286
the_web
  • 366
  • 1
  • 3
  • 10
  • Please don't indent `{`. It's very ugly. Also, your indentation style is not consistent at all. I've re-indented your code in the way it should be. – ThiefMaster Sep 20 '13 at 13:22
  • Adding the parens *calls* the function: in your case the function will be called *later*, so you only want a *reference* to the function-without parens. See the following for more details: http://stackoverflow.com/questions/7969088/when-do-i-use-parenthesis-and-when-do-i-not/7969111#7969111 – Dave Newton Sep 20 '13 at 13:25
  • Thanks Dave and everyone. – the_web Sep 30 '13 at 13:57

2 Answers2

3

What they're doing there is referring to the function without calling it.

var x = foo;   // Assign the function foo to x
var y = foo(); // Call foo and assign its *return value* to y

In JavaScript, functions are objects. Proper objects. And so you can pass references to them around.

for more clarification : In JavaScript, does it make a difference if I call a function with parentheses?

Community
  • 1
  • 1
ch.smrutiranjan parida
  • 2,302
  • 4
  • 25
  • 38
0

The function is assigned, not called. Otherwise myMother.chngName("Doe"); couldn't work since the function does not return another function. Assigning the return value of changeName() wouldn't make sense anyway, since it doesn't return anything (so it automatically returns undefined).

More detailed description: Functions are first-class objects in JavaScript. This means (besides some other things) that they can be passed around like any other value/object and assigned to any variable. In this case the function changeName which is local to the scope of the person constructor function is assigned to the object, making it available from outside (actually, from any place where the object created by new person() is available).

ThiefMaster
  • 285,213
  • 77
  • 557
  • 610