Var that = this VS dojo.hitch ()
Better to use var, which = this ;
var that = this;
array.forEach( tabPages, function ( tabPage, index ) {
that.layerTabPageClose(tabPage.id, true);
...
});
or use lang.hitch () instead
array.forEach( tabPages, lang.hitch( this, function ( tabPage, index ) {
this.layerTabPageClose(tabPage.id, true);
...
}));
Which one is better and why?
thank
source to share
In this particular case, no; use third argument to Dojo array.forEach
instead:
array.forEach(tabPages, function ( tabPage, index ) {
this.layerTabPageClose(tabPage.id, true);
...
}, this);
// ^^^^
Or use the built-in browser Array#forEach
(since ES5) and its second argument:
tabPages.forEach(function ( tabPage, index ) { // <== Note change
this.layerTabPageClose(tabPage.id, true);
...
}, this);
// ^^^^
In general:
If you create a function in the context where you are doing it (and you need var that = this
an option for), it doesn't matter and is entirely style dependent.
If you don't, you need to use lang.hitch
either ES5 Function#bind
.
source to share
It is more of a personal choice that you can make. If you prefer to use context everywhere, then you should probably use dojo/_base/lang::hitch()
so that you can work with context this
all the time.
Another option is to work with an extra variable in scope (parent) like that
or vm
(often with AngularJS), but both are great.
The only thing I would like to do is that you do the same across your entire codebase. If you are sometimes working with a scope variable and other times working with lang.hitch()
, this will only lead to confusion.
In any case, some methods, such as dojo/_base/array
, already allow you to include context:
Foreach (arr, callback, thisObject)
API Docs: http://dojotoolkit.org/api/?qs=1.10/dojo/_base/array
So there is an even better solution in these cases.
source to share