Javascript "persist" 中的构造函数(执行后可调用)如果不存储在变量中怎么办?

How can constructors in Javascript "persist" (be callable after execution) if they aren't stored in a variable?

我正在上 codeacademy.com 课,具体来说:"Javascript > Introduction to Objects I > Custom Constructors (21/33)"

在本课中,我们将学习如何创建构造函数,如下所示:

function Person(name, age) {
  this.name = name;
  this.age = age;
}

var bob = new Person("Bob", 27);

我的问题是,如果不先将构造函数放入变量中,构造函数如何在以后存在?我对 javascript 非常非常陌生,但据我了解,除非您将某些内容存储在变量中,否则它无法持久化。

这像是 class 声明吗?也许这只有 Classes?

才有可能

希望这个问题可以让我对 javascript 语法的理解有所了解。谢谢

好吧,它有点像被放在一个变量中。

function x(){}

more or less the same作为

var x = function(){} 

所以在你的情况下,你最终会得到一个名为 Person 的符号,它指向你的 function/constructor。

If the function is never assigned anywhere and never called, the compiler's dead code detection will probably remove the function before it is evaluated, so it won't even be created in the first place. Only if the function is needed, it will be created and stored in memory somewhere. But only when it is called, an actual variable unstored is created in the new scope, so that it is accessible by variable inside there.

贝尔吉

(function (name, age) {
  this.name = name;
  this.age = age;
})

不会被存储。