一直省略使用 "this."

Omit using "this." all the time

我有这样的代码

    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)); 
    }

这很烦人!而且还会影响可读性。这段代码本来可以更短......我如何在 C++ 或 Haxe 风格中使用 TS,我们不必提及“this”。任何?编译器不是很容易猜测“如果有一个变量名-检查这个名字的成员是否存在”吗?

注意: 我的问题与这个问题无关:Can I avoid using the word "this" inside Typescript when calling a function that came in through a constructor? - 在那里,开发人员询问是否可以不使用瞬态对象 属性,传递给构造函数。在我的问题中,我问是否可以在访问属性时省略“this”关键字

TypeScript(和 JavaScript)没有暗示 this

对于您只打算读取(而不是写入)的值,您可以解构为局部变量或常量:

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)); 
}

但您可能更喜欢 Crockford 风格的闭包编程。不是带有 ab 等的对象,而是函数中的局部变量 returns 带有方法的对象:

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)); 
        }
    };
}

然后,由于您对返回函数的方法关闭了创建它的调用中的局部变量,您只需直接使用 ab 等。

不过,最好尽量减少两种风格的混合。请注意,这种风格目前在 JavaScript 和 TypeScript 圈子中不像使用带有属性的对象那样流行,这可能是让其他人处理代码时的一个因素。 (尽管这只是一个训练问题。)