2

I was learning details about the new operator in JS and ran the following code in the Node.js repl.

function Foo(){
    this.x = "ecks";
    this.y = "why";
}

function Foo2(){
    this.x = "ecks";
    this.y = "why";
    return(this);
}
new Foo();
Foo2();

On this page https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new it says that the new operator makes the call to foo return this and it does work. But the second call which explicitly returns this ends up returning the global this. Why is this?

  • 5
    Because when you call `Foo2()` you don't specify a `this` value, and you are in loose mode, so the global object is used implicitly. – VLAZ Sep 14 '20 at 08:41
  • 2
    Run your code in strict mode instead of sloppy mode and `Foo2()` will cause an error (which is appropriate). That code is just wrong and strict mode stops you from doing it (which is helpful). – jfriend00 Sep 14 '20 at 08:43
  • Also relevant: [What is the 'new' keyword in JavaScript?](https://stackoverflow.com/q/1646698) and [see here about how the `new` keyword can be emulated](https://stackoverflow.com/q/58328890), perhaps it will help with understanding why `Foo2` doesn't work and how to make it equivalent. – VLAZ Sep 14 '20 at 08:45
  • I think I get it now thanks. – peter duffy Sep 14 '20 at 20:42

0 Answers0