Rishabh
Rishabh

Reputation: 900

new myFunction() returns an object with name myFunction?

I was reading the "You-Dont-Know-JS" series by Kyle Simpson and came across this code block:

function NothingSpecial() {
    console.log( "Don't mind me!" );
}

var a = new NothingSpecial();
// "Don't mind me!"

a; // {}

According to this, the last line a; should return an empty object {}. But as I see, it returns an object with name NothingSpecial (NothingSpecial {}). I am somewhat confused by this behavior. The object created by new NothingSpecial() is a, and it should be named a and not NothingSpecial, as far as I can understand. Also, the name NothingSpecial conflicts with the function name. Can anybody please explain?

Upvotes: 0

Views: 47

Answers (3)

Luke K
Luke K

Reputation: 895

I'm sure this has been covered in the book, but in JavaScript functions are just a type of object, and so can be instantiated.

Therefore, when you use the new keyword, you're creating an instance of the NothingSpecial object and binding it to a variable a. Without getting too low level, a is just a reference to that object in memory.

NothingSpecial has no variables or member functions, and so it is an empty object. It's named NothingSpecial because that's the type of object that it is. The variable "a" is essentially just a label stuck onto it so you know which instance of NothingSpecial that it is.

Upvotes: 1

Tobias
Tobias

Reputation: 7771

If you use the new keyword, prototypal inheritance is used to create an instance of something you might call a class. NothingSpecial is the class/type name and the object is therefore represented as NothingSpecial {}. This has nothing to do with the variable name, it is just the name of the class or type.

Upvotes: 2

Quentin
Quentin

Reputation: 944204

It does return an empty object. That object happens to be an instance of NothingSpecial, and the tool you are using to inspect it it is revealing that to you (it is not saying that the object is stored in a variable with that name, so there is no conflict).

Upvotes: 4

Related Questions