the_web
the_web

Reputation: 406

no () at end of variable assignment to function

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);

Upvotes: 1

Views: 72

Answers (2)

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?

Upvotes: 4

ThiefMaster
ThiefMaster

Reputation: 318508

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).

Upvotes: 1

Related Questions