Ad

Why Can't I Assign A Function To A Variable Using Prototype?

- 1 answer

I keep on trying to assign a function to a variable and I keep getting a message saying foo is not a function. I am not sure why it is saying that. When I invoke the method by itself it works, but when I assign it to a variable it won't work.

Can anyone please help me figure this out? Thank you!!!

Below is my code:

function Test(){

    function foo(){
        return "foo";
    }

    this.bar = function () {
        var foo = foo();
        console.log(foo);
    };
}
var test = new  Test();
test.bar();
Ad

Answer

Following code will work. As Now we are not trying to assign same function variable to variable.

The problem is because JavaScript is function scoped. It is failing because this.bar function will try to evaluate foo first and foo is name of variable in this function so interpreter will try to execute the foo but foo is variable in this scope it will not consider foo mentioned above. Hence it fails.

Where as foo1 will work because when interpreter hits the term foo1 it will look for current scope and all parent scopes and it will get it.

function Test(){

function foo1(){

    return "foo";
}


this.bar = function () {

    var foo = foo1();

    console.log(foo);

};

}


var test = new  Test();
test.bar();
Ad
source: stackoverflow.com
Ad