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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With