内部函数有时需要引用外部函数的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/