davidLeak
davidLeak

Reputation: 101

Why does this function work but still returns the typeError ... is not a function?

I am learning js and am confused on one thing. I am just copying/pasting the code example from mdn...

  function Person(gender) {
    this.gender = gender;
}

Person.prototype.sayGender = function() {
    alert(this.gender);
};

var person1 = new Person('Male');
var genderTeller = person1.sayGender;

person1.sayGender(); // alerts 'Male'
genderTeller(); // alerts undefined
alert(genderTeller === person1.sayGender); // alerts true
alert(genderTeller === Person.prototype.sayGender); // alerts true

in the example above genderTeller will return undefined but after slightly modifying it in the second example:

function Person(gender) {
        this.gender = gender;
    }

Person.prototype.sayGender = function() {
        alert(this.gender);
    };

var person1 = new Person('Male');
var genderTeller = person1.sayGender();
genderTeller();

the genderTeller function actually works but also returns 'typeError: genderTeller is not a function.'

Why is genderTeller not a function in the second example when it's clearly assigned to a method?

Upvotes: 0

Views: 415

Answers (2)

Mister Epic
Mister Epic

Reputation: 16733

Look at this line:

var genderTeller = person1.sayGender();

You are assigning the value returned by calling the function since you are executing it, not the function itself.

Since the function doesn't actually return a value, it's not a function (or anything at all, really), which is why you are getting that error.

Upvotes: 0

Dennis
Dennis

Reputation: 32598

In the first example, you are assigning a function to a variable and executing it. The this in that case is window, since you are just calling the function and not calling it on anything.

In the second case, you are invoking the function and assigning its result to genderTeller. Since the function doesn't return anything, the variable is undefined.

Upvotes: 3

Related Questions