stackjlei stackjlei - 1 month ago 6
Javascript Question

how does "new" work with classes in javascript?

How does the

new
work differently in the 2 examples below? I see that the 2nd example is replacing the annoymous funciton with a variable, but in the second one, the function/class "Person" is actually being called. Does it make any difference if it's being called or not? I tried it without the calling and it still worked. So that led me to believe that new is actually calling the function and setting up
this
to be assigned to the instance variable.

var person = new function() {
this.setName = function(name) {
this.name = name;
}
this.sayHi = function() {
return "Hi, my name is " + this.name;
}
}
person.setName("Rafael");
console.log(person.sayHi()); // Hi, my name is Rafael


vs.

var Person = function() {
this.setName = function(name) {
this.name = name;
}
this.sayHi = function() {
return "Hi, my name is " + this.name;
}
}

var personTwo = new Person()

personTwo.setName("Rafael");
console.log(personTwo.sayHi()); // Hi, my name is Rafael

Answer

There would be almost no difference between these two examples, if it was a simple function like this:

(function() { console.log("IIFE"); })();

// or

var f = function() { console.log("Function"); };
f();

You just store your function in a variable, and then call it.

However, it makes a little difference, since it is related to JS OOP mechanisms. In the first case you get Object instance, and in the second you get Person instance. This makes difference in OOP sense.

var person = new function() { };
console.log("Is instance of: " + person.constructor.name);
console.log("There is no way to check instanceof in this case");

var Person = function() { };
var person = new Person();
console.log("Is instance of: " + person.constructor.name);
console.log(person instanceof Person);

In general, new and classes are supposed to be used as in the second case in order to enable the full functionality of JS OOP. There is absolutely no sense or/and advantage in using anonymous class constructor.