Clear my mind on this js pattern


I see often this pattern

  (function(){}).call(this)

Is that the same with this one?

  (function(that){})(this)

Thanks in advance

EDIT

Are those two codes trying to solve the same problem? the context of this?

EDIT

Can anyone edit the title and provide a better one cause I think it is interesting.

Edited after the question:

No. Function.prototype.call accepts this as its first argument. this is not passed into a function as a real argument in this case. However, you can address the actually passed this as that in the second function.

EDIT: Here's an example.

MyObject = {};
MyObject.prototype.myMethod = function(value) { console.log("Hello, " + value); }
var obj = new MyObject();

function myMethodCaller(value)
{
    this.myMethod(value);
}

myMethodCaller("World!");
myMethodCaller.call(obj, "World!");
  • The first call will fail with an error, as [implicitly] this (receiver) will most often be the window (more generally, the global object, whatever it is in your context. It is different e.g. for workers) which does not have the myMethod method.
  • The second call will log "Hello, World!" into your console, since this will point to obj, on which the myMethod method will be called.

No it's not, the other one gives the function an object context and the other one passes an argument without any object context.

Imagine a generic function, like Array#shift():

var shift = Array.prototype.shift;

//Shift expects an object context, and cannot be called without one.


//so this won't work:
shift($("div"))
//undefined

//This does:
shift.call($("div"))
//<div id=?"notify-container">?</div>?

Are those two codes trying to solve the same problem? the context of this?

Yes, but in a different manner.

The first version invokes Function.prototype.call which as first argument, accepts the context-object to which the this variable within the called function-context will refer to.

The second version just self-invokes the anonymous function and passes the object which refers to this (in the calling context) to the anonymous function. Now, within the called anonymous function-context, we can access it via that. this will be global or undefined (depends on ES5 strict mode)