boulder_ruby
boulder_ruby

Reputation: 39743

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

I'm doing a codeacademy.com lesson, specifically: "Javascript > Introduction to Objects I > Custom Constructors (21/33)"

In this lesson we're learning how to create constructors, like so:

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

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

My question is, how can the constructor exist later on without first being placed into a variable? I'm very, very new to javascript but it was my understanding that unless you stored something in a variable it couldn't persist.

Is this like, a class declaration? Maybe this is only possible with Classes?

Hoping this question might shed some light in the dark on my understanding of javascript syntax. Thanks.

Upvotes: 0

Views: 53

Answers (2)

BBS
BBS

Reputation: 1409

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.

Bergi

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

would not be stored.

Upvotes: 1

Thilo
Thilo

Reputation: 262734

Well, it kind of is being placed in a variable.

function x(){}

is more or less the same as

var x = function(){} 

So in your case, you do end up with a symbol called Person that points at your function/constructor.

Upvotes: 1

Related Questions