0

What is the difference between

function User(name) {
  return {
    'name': name,
    'isAdmin': false,
  }
}

let user = User("Jack");

and

function User(name) {
  this.name = name;
  this.isAdmin = false;
}

let user = new User("Jack");

I do not see any real difference between the syntaxes. Why was new even added?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
adik
  • 3
  • 2
  • `return` mean you return something from function... when you use `new` , it call your function differently, (1st) It create a constructor function, (2nd) then bind `this` (object = {}) to that constructor function, (3rd) call that constructor function and returns `this` if the function doesn't return anything. – Nur Jul 03 '21 at 12:31
  • First code example does nothing special: function just returns an object. Second code example, however, does some things behind the scenes: See: [What "new" operator does](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new#description) – Yousaf Jul 03 '21 at 12:31
  • 2
    `new` creates instances, makes more sense when constructing thousands of instances, especially when methods have been used. Eg, you could create a function called Point, that has a method called distance, adding this distance method to every object is less efficient than just adding to the class prototype. – Keith Jul 03 '21 at 12:36

0 Answers0