Why is .call(this) used instead of parenthesis [duplicate] - javascript

This question already has answers here:
Reason behind this self invoking anonymous function variant
(5 answers)
Closed 8 years ago.
Is there a particular reason why i often encounter:
(function() {
console.log("Hello");
}).call(this);
instead of:
(function() {
console.log("Hello");
})();
It should have the same effect when passing this to call or not?
There seems to be some performance difference: http://jsperf.com/call-vs-parenthesis.

Presumably the code within that function uses this (where you just have console.log). In the version with call, this within the function is the same as this outside it. Without call, this inside the function is either the global object (loose mode) or undefined (strict mode).
If you're not using this within the function, there's no reason to be doing the call version, and I would lean toward not doing so because it's additional unnecessary complexity (and apparently a very very small performance cost).

The addition of .call(this) is important, it changes the context of the function enclosure, meaning that the this keyword will refer to the same this as the outer function enclosure.
In your particular code it doesn't make any difference because inside your function you do not refer to this at all.
this.a = 123;
(function() {
console.log(this.a); // always 123 regardless of scope
}).call(this);
That is significant assuming that this refers to something other than the window object. If this is already pointing to the window, then adding .call(this) makes no difference, since without it, by default the this will go to the window.

Related

Function Context in Javascript and this Keyword [duplicate]

This question already has answers here:
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 6 years ago.
Could somebody here please get this straight for all of us once and for all?
var parent = {child: function(){
console.log(this);
var log = function(){
console.log(this);};
log();
}
}
When I call parent.child()
I get:
Object{}
Window{}
Other people/ documentation on Mozilla say that this function has been invoked without any context. And
this
will be the object on which the function is invoked.
What I don't understand is how on earth this function within another object is considered to be without a context(so this defaulted to the global object). What's the logic here? Thanks
Function referenced at objects are like methods. When you directly call a function by indexing an object, this same object will be referenced by this in the scope the function will generate.
When calling a function without indexing an object, or without setting this context (with apply, bind, call, ...), if it's not at strict mode (or is at least in a global scope when at strict mode) this should be the global object.
When objects are instances of classes/interfaces/functions, their methods also capture this same object for this.
This is how it works for me:
(function() {
'use strict'
console.log(this) // undefined
})()
console.log(this) // Window{}

Scope of a named IIFE name [duplicate]

This question already has answers here:
Why does a named IIFE result in a ReferenceError outiside of it?
(2 answers)
Closed 6 years ago.
I thought I understood the nature of Immediately Invoked Function Expressions (IIFEs), but now I realise I don't.
I created an IIFE in a piece of code (in a web page using JQuery as it happens). However if I name the function, and try to call that function from the enclosing scope I get an "undefined" error?
The live code behaves differently in IE11 and Firefox 38, which makes things even more confusing. However I created a simple test JSfiddle here-
https://jsfiddle.net/ktqq4uat/
and this is consistent between browsers.
I thought these two lines-
(function myFunction2() {
...
(myFunction3= function() {
...
were pretty much equivalent, but I get an undefined error on "myFunction2" only.
I'd appreciate some help understanding-
1) Why (function myFunction2() {... is hiding the name of the function as well as it's internal scope. What IS the scope of that name?
2) Why myFunction2 and myFunction3 above behave differently.
Rgds
Named function expressions only create a variable that:
has the same name as the function
has a value that is a reference to that function
in their own scope. They also evaluate as a reference to that function so you can pass that reference somewhere (e.g. assign it to myFunction3).
Function declarations create a variable like that in their parent scope. They don't evaluate as anything (because they aren't expressions).

Why do I have to bind this function argument? [duplicate]

This question already has answers here:
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 8 years ago.
// example A (works)
foo(function() {
myObj.save();
});
// example B (doesn't work)
foo(myObj.save);
// example C (works)
foo(myObj.save.bind(myObj));
Why is the this reference correct when myObj.save is called in example A, but not in example B?
I can force this to be correct by using bind, but what is happening in example A that is different from example B?
I don't understand why this would be different.
Functions only have a context, this, when invoked.
When you call x.y(), the this context inside y is x.
When you write x.y, you're referencing just the function y, you're not invoking it and there is no context. When you pass that function elsewhere, such as z = x.y, the context is not passed with it.
You're doing that in your second example. You're passing the function without context into foo, where there is no possible way for foo to know what the context should be. When it's invoked by foo, it's going to be invoked a simple save() call, and when this happens the this context will be window (or null in strict mode).
This is because this refers to the object on which a method was called. When you set the method of a function to a variable, or pass it in as an argument, it is no longer associated with the object it was a method of.
Multiple objects can share the same function, this is a way of dynamically reusing that function to manipulate the object instance it is a method of.
The bind method was added later to address use cases such as these.

What is the "this" pointer for global functions? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
'this' keyword, not clear
this operator in javascript
function foo()
{
if(this === window)
return null;
return 1;
}
var i = foo(); // returns 1;
What is the this member of a global function, and how can I test from within a function if it's being called in a global scope or as a member function?
Edit: It seems JQuery makes a difference here, since everybody assures me foo should return null for run-of-the-mill JavaScript. How does JQuery change this?
Note that the OP says, in a comment, below, that this is in a Greasemonkey script.
According to this the difference is because of greasemonkey (not JQuery).
A Greasemonkey user script, however, by default wraps up all code inside an anonymous function wrapper that swallows identifiers, causing them not to end up on the global object.
It goes on to say that you can use #unwrap to make this point to the window as it does with regular on-page Javascript.
this refers to the window object in this case.
Just do alert(this); and it will say [object Window]
But if you do
var i = new foo(); // returns an object (instance of foo);
then this refers to the instance of foo.
The this member refers to the entire page, and will always be defined - your foo() method will never return null.
this always points on the current element. In the case of foo(), this points to window.

Why are parenthesis used to wrap a javascript function call? [duplicate]

This question already has answers here:
Are "(function ( ) { } ) ( )" and "(function ( ) { } ( ) )" functionally equal in JavaScript? [duplicate]
(3 answers)
Closed 9 years ago.
What is the difference between these two javascript function calls?
(function(){alert("foo")})()
versus this:
(function(){alert("foo")}())
This is done for readability.
There isn't a real functional difference between the two examples you've given, but both of them are very close to a simple function declaration, which is different. The parenthesis are added for readability, in order to distinguish them.
Here is what each of your snippets do:
In the first of your two snippets, the first parenthesis will be evaluated as the value of the enclosed function. Then this value will be called as a function. So ultimately the function will be executed, which is probably what you care about.
In your second snippet, the outer parenthesis will be evaluated as containing a function which is declared inline and immediately executed. Again, the function will be executed, which is still probably what you care about.
Both of these will execute the same function, so there won't be any significant difference.
The difference between a snippet like yours and a simple function declaration:
The functions you've given are also identical to the following. I've just added a function name and assigned the return value for syntactical accuracy, which you can ignore for now.
// javascript...
var val =
function myFooFunc () {
alert("foo");
}();
However, this would be easily mistaken for a simple function declaration, which is different:
// javascript...
function myFooFunc () {
alert("foo");
}
Notice that the only real difference here is that this last function declaration is not executed immediately. The others are. So that is a very different behavior (the simple declaration may be executed later if it is called by name, or it may not ever execute at all). It's often hard to see that difference in the syntax right away, however, especially if the function body grows to be very long and requires scrolling on the screen.
Why are functions executed immediately?
When a function is immediately executed after it is declared, the value is often being returned to something (it may be part of an assignment statement). Sometimes the function is being executed right away because it contains inner functions and is being used to provide functional scope to the inclosed statements.
Essentially, people wrap parenthesis around the "executed immediately" form (both of your snippets, and the first one of my two) in order to give a visual cue to other developers that the function is being called immediately. It's just easier to read, since you might not catch the parenthesis until you got to the end of the function (or notice them at all).
They both have similar behaviors.
The parentheses encapsulating the function declaration tell the JavaScript engine to execute the code immediately after it's parsed. In the first example, you're creating a function object then invoking it with the parentheses that follow. In the second example, you are telling the JavaScript engine to create the function object and invoke it immediately.
Example:
// creates a function object
var f1 = (function() { alert('foo'); });
// creates a function object and executes it immediately
var f2 = (function() { alert('foo'); }());
The difference is that f1 gives you a function object. f2 creates and invokes an anonymous function.

Categories

Resources