I am studying how to create some plugins using angularjs
and in some of them I have faced this:
(function() {
'use strict'
//code...
}).call(window);
what is the difference from just using a self-invoking function like that below?
(function() {
'use strict'
//code...
})();
The two invocations will have different this
values.
This code
(function() {
'use strict'
console.log(this)
})();
will log undefined
because direct non-method invocations of strict-mode functions use a this
value of undefined
.
This code
(function() {
'use strict'
console.log(this)
}).call(window);
will log window
since the first argument to call
is used to supply this
to the function being invoked.
If I had to guess, I'd say this is being done to mimic the non-strict behavior of using window
(instead of undefined
) for this
of a bare non-method invocation. Simply use window
if you mean window
.