Why write “.call(this)” at the end of an javascript anonymous function? [duplicate]

Try this:

function Foo() {

  (function () {
    console.log(this);
    // > Foo
  }).call(this);

  (function () {
    console.log(this);
    // > undefined in strict mode, or Window in non strict mode
  })();
}

var bar = new Foo;

So, if for whatever reason you use this, it’s a way to make the IIFE act as if it were a member function of Foo, specifically when creating instances of a user-defined object type.

Leave a Comment