1

I am not able to understand the following code,

function Foo(arg) { 

  if (!(this instanceof Foo)){
      alert("inside if statement");
      return new Foo(arg);
  }

  else{
    alert("inside else statement")
  }

  this.myArg = arg;

}

let foo_obj = Foo("bar");
alert(foo_obj.myArg);

When the program is executed, when if statement is first encountered, it checks whether "this" (which is the window object then) has "Foo" in its prototype chain, since it is not there the following is executed

return new Foo(arg);

So Foo is called again, but this time the "else" part is executed. Why is that so? What is the value of "this" the second time?

jibin mathew
  • 447
  • 7
  • 13
  • The `new` operator initializes a new object and calls the constructor with `this` a reference to it. – Pointy Nov 23 '18 at 17:16
  • In JavaScript a class constructor is a function (well it's a function in all languages) so you can in practice call the function directly (you usually can't in other languages) instead of using it to construct a class. That if / else there just differentiates between the function being used as a constructor (with `new`) or being called as a function (without `new`). – apokryfos Nov 23 '18 at 17:18
  • It's just to make it so that `var obj = Foo("bar")` does the same as `var obj = new Foo("bar")`, IOW: it's just to make sure a new instance of Foo is created,. – Keith Nov 23 '18 at 17:18
  • 1
    @Pointy So "this" refers to the object initialized in the constructor function when called with "new"? – jibin mathew Nov 23 '18 at 17:18
  • 2
    Yes, if called with `new`, `this` will equal an instance of `Foo`, but if it's not called with `new` it will be undefined, or window if not in strict mode. Personally I don't like this instancing shorthand, if you want a new instance of an object, is more specific for it to have `new Class()`,. if you want to force the constructor to use `new`, I would personally throw an exception instead. – Keith Nov 23 '18 at 17:19
  • @Keith Thank you, for the clarification. – jibin mathew Nov 23 '18 at 17:23

0 Answers0