如果JS中的函数是一流的,那么它们在被定义之前是否可以被调用? [英] If functions in JS are first-class, what allows them to be called before they are defined?

查看:149
本文介绍了如果JS中的函数是一流的,那么它们在被定义之前是否可以被调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不要一流的功能意味着它们表现为变量?显然,它们的行为并不像变量一样,因为这是:

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

...不起作用,而这:

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

... does。



即是说:

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

不起作用,这是更一致的。



给出了什么?

解决方案

因为你没有比较相同的东西。在你的例子中 - 你在<$>中比较函数声明 函数foo()... 变量声明和赋值 c $ c> var foo ='bar';



更正确的比较是:

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

with

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

函数声明方式吊装起作用。提升将所有声明移动到最接近的作用域的顶部,将作业留在位置。



函数声明。在这个意义特殊,因为这既是宣言和表达/分配在一个声明中,因此悬挂在一起。



举个例子:你可以看看像表达式:

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

如下:

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

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

b

$ b $ p
$ b



$ b

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


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?

解决方案

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';
}

这篇关于如果JS中的函数是一流的,那么它们在被定义之前是否可以被调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆