无法从函数内部覆盖函数 [英] Cannot overwrite function from inside the function

查看:80
本文介绍了无法从函数内部覆盖函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到了意想不到的结果。这是代码:

I got an unexpected result. Here's the code:

b = function c() {
  console.log(c);
  c = 3;
  console.log(c);
}
b();

I认为第二个console.log应该打印3,但我得到了功能本身。为什么?

I thought the second console.log should print "3" but instead I got the function itself. Why?

同时,从下面的代码我得到了正确的3。

Meanwhile, from the code below I got the right "3".

function ff() {
  ff = 3;
  console.log(ff);
}
ff();

推荐答案

您使用的是 函数表达式

You are using a function expression:


FunctionExpression:

函数标识符 opt (FormalParameterList opt
){FunctionBody}

FunctionExpression :
function Identifieropt ( FormalParameterListopt ) { FunctionBody }

所以 b = function c(){...}; 完全有效,严格模式或其他方式。 c 会发生什么问题。根据规格:

So b = function c() { ... }; is perfectly valid, strict mode or otherwise. What happens to c is another question. According to the specs:


生产

FunctionExpression:函数标识符(
FormalParameterList opt ){FunctionBody}

评估如下:

The production
FunctionExpression : function Identifier ( FormalParameterListopt ) { FunctionBody }
is evaluated as follows:

[...]

3.致电envRec
CreateImmutableBinding 具体方法将Identifier的String值作为参数传递。

4.让闭包成为创建新Function对象的结果
,如13.2 [...]中所述|
5.调用envRec
的InitializeImmutableBinding具体方法,将Identifier和closure的String值作为参数传递。

[ ...]

[...]
3. Call the CreateImmutableBinding concrete method of envRec passing the String value of Identifier as the argument.
4. Let closure be the result of creating a new Function object as specified in 13.2 [...]
5. Call the InitializeImmutableBinding concrete method of envRec passing the String value of Identifier and closure as the arguments.
[...]

注意

FunctionExpression中的标识符可以在FunctionExpression的FunctionBody中从
引用,以允许函数为
递归调用自身。但是,与FunctionDeclaration不同,FunctionExpression中的
标识符无法引用,并且
不会影响包含FunctionExpression的范围。

NOTE
The Identifier in a FunctionExpression can be referenced from inside the FunctionExpression's FunctionBody to allow the function to call itself recursively. However, unlike in a FunctionDeclaration, the Identifier in a FunctionExpression cannot be referenced from and does not affect the scope enclosing the FunctionExpression.

所以:


  • c 在函数内可见

  • c 无法从函数内部覆盖(不可变绑定)

  • c is visible inside the function but not outside it
  • c cannot be overwritten from inside the function (an "immutable" binding)

同时,从下面的代码我得到了正确的3。

function ff(){

这是函数声明;这里适用不同(更明显)的规则。

This is a function declaration; different (and more obvious) rules apply here.

这篇关于无法从函数内部覆盖函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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