Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear my mind on this js pattern

Tags:

javascript

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.

like image 749
chchrist Avatar asked Dec 16 '25 22:12

chchrist


2 Answers

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>​
like image 183
Esailija Avatar answered Dec 19 '25 12:12

Esailija


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.
like image 23
Alexander Pavlov Avatar answered Dec 19 '25 11:12

Alexander Pavlov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!