3
votes

When using getters and setters in object literals, I cannot see an easy way to access the outer "this" scope in Typescript. Consider the following:

class Report {
    stuff: any[];

    options = {
        length: 10,
        get maxLength() { return REPORT.stuff.length }
    }
}

Where REPORT wants to be a reference to the instance of the Report object. I realize that I can solve this by setting options within the constructor and using a var REPORT = this or similar, but seems inelegant. Is there a way to do this more cleanly?

2

2 Answers

7
votes

I realize that I can solve this by setting options within the constructor and using a var REPORT = this or similar, but seems inelegant

Instead of setting up option in the constructor you can take advantage of the fact that options *is being defined in the constructor. Thus, store this into options:

class Report {
    stuff: any[] = [];

    options = {
        _report: this,
        length: 10,
        get maxLength() { return (this._report as Report).stuff.length }
    }
}

let foo = new Report(); 
foo.stuff = [1,2];
console.log(foo.options.maxLength); // 2
2
votes

You can take advantage of the this binding of lambdas.

class Report {
    stuff: any[];

    options = {
        length: 10,
        maxLength: () => this.stuff.length
    }
}

compiles to

var Report = (function () {
    function Report() {
        var _this = this;
        this.options = {
            length: 10,
            maxLength: function () { return _this.stuff.length; }
        };
    }
    return Report;
})();

Edit: This makes a function instead of a getter like you originally had. I assumed that was a typo, until just now, when I just learned that's valid javascript.