gpt4 book ai didi

javascript - 在内部函数中消除歧义

转载 作者:行者123 更新时间:2023-11-30 05:34:49 24 4
gpt4 key购买 nike

内部函数有时需要引用外部函数的this。 JavaScript 是否有一个广泛使用的习惯用法?我想出了一个解决方案,涉及将 this 分配给另一个变量:

Object.defineProperty(Array.prototype, 'set', {
enumerable: false,
value: function (a) {
this.length = 0
var this1 = this
a.forEach(function (x) {
this1.push(x)
})
}
})

但我不确定这是否是最简洁或最惯用的解决方案。

最佳答案

我个人使用 that 作为变量名,而不是 this1,但除此之外,它既干净、传统又符合 Javascript 的习惯。

Douglas Crockford似乎也推荐使用 that

By convention, we make a private that variable. This is used to make the object available to the private methods. This is a workaround for an error in the ECMAScript Language Specification which causes this to be set incorrectly for inner functions.

过去,我也看到有人使用 self

关于javascript - 在内部函数中消除歧义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24566514/

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