簡體   English   中英

如何在課堂上進行全局解構?

[英]How to make a global destructuring form this in class?

例如,我正在嘗試在課堂上對此進行全局解構

class Car {
    constructor(
        color,
        speed,
        type,
    ) {
        this.color = color;
        this.speed = speed;
        this.type = type;
    }

    method1() {
      const { color, speed, type } = this;
      // do something with speed, color, type;
    }

    method2() {
        const { color, speed, type } = this;
        // do another thing with speed, color, type;
    }

    method3() {
        const { color, speed, type } = this;
        // do another thing with speed, color, type;
    }
}

不是在每個方法中解構它,而是有一種方法可以將其作為所有方法的全局

在每個方法中,我只是引用變量而不是調用它

不,那里沒有。 如果你想在每個方法中創建局部變量,你不能全局這樣做。

唯一的選擇是不使用class而是使用工廠函數,該函數在構造函數參數上構建閉包:

function Car(color, speed, type) {
    return {
        get color() { return color; },
        get speed() { return speed; },
        get type() { return type; },
        method1() {
          // do something with speed, color, type;
        },
        method2() {
            // do another thing with speed, color, type;
        },
        method3() {
            // do another thing with speed, color, type;
        }
    };
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM