“this” and Function.createDelegate in JSOM

By on May 7, 2013,

There are two prevailing methods of registering a callback for the executeQueryAsync function:

context.executeQueryAsync(

    Function.createDelegate(this, _onSucceed), 

    Function.createDelegate(this, _onFail)

);

and:

context.executeQueryAsync(_onSucceed, _onFail);

As you can see, the difference is simply the inclusion or exclusion of the Function.createDelegate call.  If you’ve always wondered what the difference between the two was, as I have, the answer is pretty simple: the former allows you to override what the value of the this variable will be inside the function.

In the latter case, not using Function.createDelegate, when you are inside either the _onSucceed or _onFail  callbacks, this will reference the callback function itself – onSucceed or onFail  respectively.

In the former case, using Function.createDelegate, when you are inside either the _onSucceed or _onFail callbacks, this will reference whatever you pass in as the first parameter to the createDelegate function.  In this example, we’re passing in the current value of this, so inside the callback, this will be the same as in the function that made the call to createDelegate.  It’s important to note that you can pass any object in as that first parameter:

Function.createDelegate(window, _onSucceed) 

Function.createDelegate(new myWidget(), _onSucceed)

Function.createDelegate({}, _onSucceed)

Function.createDelegate(someOtherObject, _onSucceed)

 

will all work fine, making this equal to window, a new instance of myWidget, an empty object, and whatever object is represented by someOtherObject, respectively.

Tags ,