最好使用 var = this ;

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

或改用 lang.hitch()
array.forEach( tabPages, lang.hitch( this, function ( tabPage, index ) {
  this.layerTabPageClose(tabPage.id, true);
  ...
}));

哪一个更好,为什么?

谢谢

最佳答案

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

array.forEach(tabPages, function ( tabPage, index ) {
  this.layerTabPageClose(tabPage.id, true);
  ...
}, this);
// ^^^^

或使用浏览器的内置 Array#forEach (从ES5开始)及其第二个参数:
tabPages.forEach(function ( tabPage, index ) { // <== Note change
  this.layerTabPageClose(tabPage.id, true);
  ...
}, this);
// ^^^^

通常情况下:

如果要在执行此操作的上下文中创建函数(并且必须将var that = this选为选项),则无关紧要,而完全取决于样式。

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

关于javascript - var that = this VS dojo.hitch(),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30213661/

10-10 09:10