知道JavaScript函数表达式与函数声明,但这是什么?命名函数表达式? [英] Know JavaScript Function Expression vs Function Declaration, but what is this? Named Function Expression?

查看:130
本文介绍了知道JavaScript函数表达式与函数声明,但这是什么?命名函数表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

JavaScript:var functionName = function(){} vs function functionName(){}

Javascript中函数表达式与声明之间有什么区别?


我知道函数声明和表达式之间的区别,但是遇到了涉及函数名称的代码,想要了解会发生什么当我们运行它时:

I am aware of the differences between Function Declarations and Expressions, but have come across this code involving function name and want to understand what happens when we run it:

var abc = function def() {
    console.log("Wait! What??");
}

我知道这不是JavaScript的一种方式,但只是想知道一些事情:

I know that this is not a way to JavaScript, but just want to know few things:


  1. abc 会怎样?为什么会这样?可以调用 abc 但不能 def ,为什么?

  2. 这是一个吗?函数声明或表达式?

  3. def undefined - 为什么?如果它应该是,是否有
    内存泄漏?

  4. 为什么 abc.prototype 是函数 def

  1. What happens to abc? Why it works? abc can be called but not def, why?
  2. Is it a function declaration or an expression?
  3. def is undefined - why? If it is supposed to be, are there memory leaks?
  4. Why is abc.prototype is function def?

谢谢

推荐答案


abc会发生什么?

What happens to abc?

它包含一个函数宾语。如果你什么都不做,它将被垃圾收集。

It contains a function object. If you are doing nothing with it, it will be garbage-collected.


为什么会这样?

Why it works?

为什么不呢?什么有用?

Why not? What "works"?


可以调用abc而不是def,为什么?

abc can be called but not def, why?

这只适用于外部,而不适用于IE。见下文。

This is only true from outside, and not in IE. See below.


是函数声明还是表达式?

Is it a function declaration or an expression?

这是一个函数表达式。您可以很容易地看到它,因为它是赋值表达式的一部分;声明总是需要在顶层(函数或全局代码)

It is a function expression. You can easily see that as it is part of an assignment expression; declarations always need to be on top level (of functions or global code)


def未定义 - 为什么?

def is undefined - why?

仅限外线。函数表达式不会创建变量。 def是函数的名称 ,在函数内部,它也是对函数的引用。这允许递归,例如不使用任何外部变量。

Only from outside. A function expression does not create variables. "def" is the name of the function, and inside the function it is a reference to the function as well. This allows recursion for example without using any outer variables.

var abc = function def() {
    def === abc; // true
    def.name; // "def"
}
abc();
def; // undefined




如果应该是,那么是否有内存泄漏?

If it is supposed to be, are there memory leaks?

是,在Internet Explorer中。它从该代码创建了两个不同的函数。有关详细信息,请参阅 http://kangax.github.com/nfe/#jscript-bugs

Yes, in Internet Explorer. It creates two distinct functions from that code. For the details, see http://kangax.github.com/nfe/#jscript-bugs


为什么abc.prototype是函数def?

Why is abc.prototype is function def?

事实并非如此。这只是一个对象。也许它在你的控制台中以该名称显示,属于名为def的函数。

It is not. It is just an object. Maybe it is shown with that name in your console, as belongs to a function named "def".

这篇关于知道JavaScript函数表达式与函数声明,但这是什么?命名函数表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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