TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

Scoping problem

Open bworwa opened this issue 12 years ago • 1 comments

Follow the variable attributes along this next example:

class Foo
{
    private attributes = {
        bar: true,
    };

    baz()
    {
        this.attributes.bar; // true

        Object.keys(someObject).forEach(function(key) {
            this.attributes[key] = configuration[key]; // this.attributes = undefined
        });

        // However, if we add the following line
        var keys =  this.attributes;

        Object.keys(someObject).forEach(function(key) {
            keys[key] = configuration[key]; // this works and modifies this.attributes as expected
        });
    }
}

bworwa avatar Aug 05 '14 19:08 bworwa

TypeScript has the same this semantics as JavaScript.

RyanCavanaugh avatar Aug 05 '14 19:08 RyanCavanaugh