rwallace
rwallace

Reputation: 33505

Disambiguating this in inner functions

Inner functions sometimes need to refer to this of an outer function. Does JavaScript have a widely used idiom for such? I came up with a solution involving assigning this to another variable:

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

But I'm not sure whether this is the cleanest or most idiomatic solution.

Upvotes: 2

Views: 40

Answers (1)

Robby Cornelissen
Robby Cornelissen

Reputation: 97322

I personally use that as a variable name instead of this1, but other than that it's both clean, conventional and idiomatic Javascript.

Douglas Crockford also seems to recommend using 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.

In the past, I've also seen people using self.

Upvotes: 1

Related Questions