zod zod - 5 months ago 8
Javascript Question

Why write ".call(this)" at the end of an javascript anonymous function?

I have seen JavaScript written like this (it was at a demonstration, and I don’t have the actual code at hand, but it was implied this was normal):

(function() {

var a = 1;

this.sayA = function() {
alert(a);
}

}).call(this);

sayA();


I suppose it is written an an anonymous function so that the variable
a
is not globally available.

What could the point of the
.call(this)
be? Since this function was not nested,
this
was just the window. How does it differ from just writing
()
at the end?

Answer

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.