var that = this VS dojo.hitch()

max*_*ver 3 javascript dojo

使用var = this是否更好;

var that = this;
array.forEach( tabPages, function ( tabPage, index ) {
  that.layerTabPageClose(tabPage.id, true);
  ...
});
Run Code Online (Sandbox Code Playgroud)

或者使用lang.hitch()代替

array.forEach( tabPages, lang.hitch( this, function ( tabPage, index ) {
  this.layerTabPageClose(tabPage.id, true);
  ...
}));
Run Code Online (Sandbox Code Playgroud)

哪一个更好,为什么?

谢谢

T.J*_*der 5

在这种特殊情况下,都不是; 使用Dojo的第三个参数array.forEach:

array.forEach(tabPages, function ( tabPage, index ) {
  this.layerTabPageClose(tabPage.id, true);
  ...
}, this);
// ^^^^
Run Code Online (Sandbox Code Playgroud)

或者使用浏览器的内置Array#forEach(从ES5开始)及其第二个参数:

tabPages.forEach(function ( tabPage, index ) { // <== Note change
  this.layerTabPageClose(tabPage.id, true);
  ...
}, this);
// ^^^^
Run Code Online (Sandbox Code Playgroud)

在一般情况下:

如果你在你正在做这个的上下文中创建一个函数(并且你必须,为了var that = this一个选项),它并不重要,完全是一个风格的问题.

如果不是,则需要使用lang.hitch或ES5 Function#bind.