Consider the following examples:

var company = 'Apple',
    log = console.log;

function f1() {
    log(company);
    var company = 'Twilio';
    log(company)
}

function f2() {
    log(company());

    function company() {
        return 'Zynga';
    }
}

function f3() {
    log(company());
    var company = function() { return 'RIM'; };
}

log(company);
log('---');
f1();
log('---');   
f2();
log('---');
f3();

The output from firebug is:

"Apple"
---
undefined
"Twilio"
---
"Zynga"
---
TypeError: company is not a function

So why is hoisting in f3 giving me the error while others are working just fine?

有帮助吗?

解决方案

Let's rewrite your f3 function to show what it would look like after variable hoisting:

function f3() {
    log(company());
    var company = function() { return 'RIM'; };
}

becomes:

function f3() {
    var company; // declaration hoisted

    log(company());
    company = function() { return 'RIM'; };
}

Now you can see that you are attempting to execute an undefined variable, not a function (hence the "not a function" error).

Note that this is difference from the output of f2 because function declarations are hoisted as a unit.

其他提示

The variable is hoisted, but setting it is not.

The value of company in f3 is not set until after log(company()) is called. You can see the same behavior in f1.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top