gpt4 book ai didi

javascript - var that = this VS dojo.hitch()

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:45:02 25 4
gpt4 key购买 nike

使用var that = 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com