TypeScript
TypeScript copied to clipboard
Scoping problem
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
});
}
}
TypeScript has the same this semantics as JavaScript.