If functions in JS are first-class, what allows th

2020-02-27 17:46发布

Don't first class functions mean that they behave as variables? Clearly they don't behave exactly like variables though, since this:

console.log(foo);
var foo = 'bar';

...doesn't work, whereas this:

console.log(foo());
function foo() {
 return('bar');
}

...does.

That said, this:

console.log(foo());
var foo = function() { return 'bar'; };

doesn't work, which is more consistent.

What gives?

4条回答
一纸荒年 Trace。
2楼-- · 2020-02-27 18:19

Function declarations are automatically bumped to top of the scope in JS

console.log(foo());
function foo() {
 return('bar');
}

is actually interpreted as

function foo() {
 return('bar');
}
console.log(foo());

the second bit of code is working that way, because foo is variable, not a function (it just happens to have an anonymous function as a value). Variables are also bumped to top, so

console.log(foo());
var foo = function() { return 'bar'; };

becomes

var foo; //empty variable
console.log(foo()); //undefined
foo = function() { return 'bar'; }; //creates a function without name and assigns it to foo
查看更多
Animai°情兽
3楼-- · 2020-02-27 18:23

Because you don't compare the same thing. In your example - you compare function declaration function foo()... with variable declaration and assignment in var foo = 'bar';

A more correct comparison would be of:

console.log(foo);
var foo = 'bar';

with

console.log(foo());
var foo = function() {
 return 'bar';
}

The functional declaration is interpreted differently due to the way hoisting works. Hoisting moves all declarations to the top of the closest scope, while leaving assignments in their place.

Function declaration is special in that sense, since it's both declaration and expression/assignment in one statement and thus hoisted together.

As an example: you can look at expressions like:

console.log(foo);
var foo = 'bar';

as this:

var foo;
console.log(foo); //prints undefined
foo = 'bar';

and

console.log(foo());
var foo = function() {
 return 'bar';
}

as this:

var foo;
console.log(foo());
foo = function() {
 return 'bar';
}
查看更多
我欲成王,谁敢阻挡
4楼-- · 2020-02-27 18:36

What you're experiencing is called hoisting. When using a function declaration like:

function foo() {}

foo will be moved to the top of the closest scope (function).

On the other hand when you use a function expression or function assignment like:

var foo = function() {}

the variable foo will be moved to the top but the assignment will occur when is needed.

Learn more

查看更多
地球回转人心会变
5楼-- · 2020-02-27 18:45

Function declaration and variable declaration will always be moved to the top of their scope.

console.log(foo());
function foo() {
   return 'bar';
}

is interpreted as:

function foo() {
   return 'bar';
}
console.log(foo());

console.log(foo());
var foo = function () {
   return 'bar';
};

is interpreted as:

var foo;
console.log(foo());
foo = function () {
   return 'bar';
};
查看更多
登录 后发表回答