Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - understand methods

I have doubts about understanding the principles of methods.
I understand functions and I know that

function hello() {
    alert('Hello World');
}  

is the same as

var hello = function() {
    alert('Hello World');
}  

Now, what's my problem is.
Here is my object with one method. I don't understand why parenthesis are don't needed at yarsLeft inside function people()
I am looking for a logical explanation.

function people(name, age) {
    this.name = name;
    this.age = age;
    this.yearsUntilRetire = yearsLeft; // this is confised for me
}

function yearsLeft() {
    var numYears = 65 - this.age;
    return numYears;
}

Create object

var test = new people('Superman', 50);
test.yearsUntilRetire(); // I understand this code and calling a method in that way

Why I can't write this.yearsUntilRetire() = yearsLeft or this.yearsUntilRetire = yearsLeft();

like image 554
rflw Avatar asked Jan 07 '23 20:01

rflw


1 Answers

When you use the name of a function without parentheses ( ()) you are setting a reference to the function itself.

When you use the same function with parentheses you are executing the function.

Therefore this line

this.yearsUntilRetire = yearsLeft;

Is setting yearsUntilRetire to point to the function. Thereafter you can do this:

this.yearsUntilRetire(); // execute the yearsLeft function.

Why I can't write this.yearsUntilRetire() = yearsLeft or this.yearsUntilRetire = yearsLeft();

In the first case, you cannot set the result of calling a function to a different result - it is a syntax error.

In the second case, you can - it sets the variable yearsUntilRetire to the result of calling the function yearsLeft

like image 152
Jamiec Avatar answered Jan 14 '23 19:01

Jamiec