javascript - Invoking a function expression with hanging Parens Vs Function.prototype.call -
what difference between using standard hanging parens method invoking function expression , using .call
in javascript?
i see iifes invoked like
(function(){ //your code here }).call(this);
as opposed more standard
(function(){ //your code here })();
what advantage of using .call
if any?
it depends on scope.
if in global scope, using .call(this)
has absolutely 0 effect because this
window
object.
if in nested scope somewhere, , want use thisbinding
(this
) using .call(this)
important (or storing this
in variable such self
or that
). iife going executing @ global scope, this
binding going change window
. if attempt use this
made in scope, , this
isn't bound, referencing wrong object.
here example:
window.x = 5; (function(){ console.log(this.x);//5 })() var obj = { x : 6, test : function(){ (function(){ console.log(this.x);//5 })() }, close : function(){ (function(){ console.log(this.x);//6 }).call(this) } }; obj.test(); obj.close();
Comments
Post a Comment