Getter的行为与方法

时间:2018-06-13 11:24:41

标签: javascript typescript ecmascript-5

我正在用TypeScript重写一个库,我已将函数calcPosition更改为getter position。他们都有几乎完全相同的代码:

public calcPosition (x : number, y : number, w : number, h : number) : Position {
    const colWidth = this.columnWidthInPX;
    if (this.rightToLeft) {
        return {
            right: Math.round(colWidth * x + (x + 1) * this.margin[0]),
            top: Math.round(this.rowHeight * y + (y + 1) * this.margin[1]),
            width: w === Infinity ? w : Math.round(colWidth * w + Math.max(0, w - 1) * this.margin[0]),
            height: h === Infinity ? h : Math.round(this.rowHeight * h + Math.max(0, h - 1) * this.margin[1])
        };
    } else {
        return {
            left: Math.round(colWidth * x + (x + 1) * this.margin[0]),
            top: Math.round(this.rowHeight * y + (y + 1) * this.margin[1]),
            width: w === Infinity ? w : Math.round(colWidth * w + Math.max(0, w - 1) * this.margin[0]),
            height: h === Infinity ? h : Math.round(this.rowHeight * h + Math.max(0, h - 1) * this.margin[1])
        };
    }
}

get position () : Position {
    const colWidth = this.columnWidthInPX;
    if (this.rightToLeft) {
        return {
            right: Math.round(colWidth * this.innerX + (this.innerX + 1) * this.margin[0]),
            top: Math.round(this.rowHeight * this.innerY + (this.innerY + 1) * this.margin[1]),
            width: this.innerW === Infinity ? this.innerW : Math.round(colWidth * this.innerW + Math.max(0, this.innerW - 1) * this.margin[0]),
            height: this.innerH === Infinity ? this.innerH : Math.round(this.rowHeight * this.innerH + Math.max(0, this.innerH - 1) * this.margin[1])
        };
    } else {
        return {
            left: Math.round(colWidth * this.innerX + (this.innerX + 1) * this.margin[0]),
            top: Math.round(this.rowHeight * this.innerY + (this.innerY + 1) * this.margin[1]),
            width: this.innerW === Infinity ? this.innerW : Math.round(colWidth * this.innerW + Math.max(0, this.innerW - 1) * this.margin[0]),
            height: this.innerH === Infinity ? this.innerH : Math.round(this.rowHeight * this.innerH + Math.max(0, this.innerH - 1) * this.margin[1])
        };
    }
}

每次从库中调用calcPosition方法时,它都会使用相同的参数调用它:

pos = this.calcPosition(this.innerX, this.innerY, this.innerW, this.innerH);

正如您在上面所看到的,我做了一件非常明智的事情,将它转换为直接使用这些属性的getter,而不是将它们作为参数传递。请注意,这些属性是简单类型 - 数字,而不是对象 - 所以我怀疑这与参考问题有关。然而,通过将单行(上面一行)更改为使用this.position而不是this.calcPosition(),我的应用程序的行为会有所不同。 是什么原因导致我的getter行为与我的方法不同?

0 个答案:

没有答案