Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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?

like image 670
zod Avatar asked Nov 07 '11 11:11

zod


People also ask

What does .call do in JavaScript?

The call() method is a predefined JavaScript method. It can be used to invoke (call) a method with an owner object as an argument (parameter). With call() , an object can use a method belonging to another object.

Why is this undefined in function JavaScript?

This is a common JavaScript error that happens when you try to call a function before it is defined. You get this error when you try to execute a function that is uninitialized or improperly initialized . It means that the expression did not return a function object.

Why is this undefined in strict mode?

In strict mode, it is now undefined . When a function was called with call or apply , if the value was a primitive value, this one was boxed into an object (or the global object for undefined and null ). In strict mode, the value is passed directly without conversion or replacement.

How can this be undefined?

A variable that has not been assigned a value is of type undefined . A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value. A function returns undefined if a value was not returned. Let's try to understand by a simple example.


1 Answers

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.

like image 187
Yoshi Avatar answered Oct 05 '22 18:10

Yoshi