1

I have pieces of code like

    get ab(){ 
        if(this.a == this.b) this.c = this.a.add(this.b);
        if(this.d == this.b) this.d = this.a.add(this.b, this.bIdx).normalize();
        return this._ab || 
               (this._ab = new Edge(this.allPoints, this.aIdx, this.bIdx)); 
    }

which is annoying! And also affects readability. This code could have been way shorter... How can I use TS in C++ or Haxe style, where we don't have to mention "this." whatsoever? Isn't it easy for a compiler to make a guess that "if there is a variable name - check if a member of this name exists"?

NOTE: my question has nothing to do with this one: Can I avoid using the word "this" inside Typescript when calling a function that came in through a constructor? - in there, a developer asks if it's possible not to use a transient object property, that was passed into the constructor. In my question, I ask if it's possible to omit "this" keyword when accessing properties

5

1 Answer 1

3

TypeScript (and JavaScript) don't have implied this.

For the values you're only going to read (rather than write), you can destructure to local variables or constants:

get ab(){ 
    const {a, b, d, aIdx, bIdx, _ab} = this;
    if(a == b) this.c = a.add(b);
    if(d == b) this.d = a.add(b, bIdx).normalize();
    return _ab || 
           (_ab = new Edge(allPoints, aIdx, bIdx)); 
}

But you may prefer Crockford-style closure programming. Instead of an object with a, b, etc. on it, you have local variables in a function that returns an object with methods on it:

function createExample() {
    let a, b, c, d, aIdx, bIdx, _ab;

    // ...

    return {
        ab() {
            if(a == b) c = a.add(b);
            if(d == b) d = a.add(b, bIdx).normalize();
            return _ab || 
                   (_ab = new Edge(allPoints, aIdx, bIdx)); 
        }
    };
}

Then since your methods on the returned function close over the locals in the call that created it, you just use a, b, etc. directly.

Best to minimize mixing the two styles, though. And just be aware that this style is currently not as popular in JavaScript and TypeScript circles as using objects with properties on them, which can be a factor when having others work on the code. (Though that's just a training issue.)

2
  • More or less, it will do :) But it makes copies, so I can't do "property = value", I have to "this.property = value", right?
    – shal
    Jan 18, 2021 at 9:54
  • 1
    @shal - Right, that's why I have this.c = and this.d = above, and part of the reason for using const (so that if you forget, you get a clear error rather than just...not seeing the change happen). Jan 18, 2021 at 9:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.