亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Javascript 靜態方法鏈接

Javascript 靜態方法鏈接

UYOU 2023-05-11 16:29:40
我可以在 javascript 中鏈接靜態方法嗎?這是我正在嘗試做的一個例子test.js'use strict'class testModel{  static a(){         return "something that will be used in next method"  }  static b(){    let previousMethodData = "previous method data"    return "data that has been modified by b() method"  }}module.exports = testModel然后我希望能夠像這樣調用方法const value = testModel.a().b()
查看完整描述

1 回答

?
慕碼人8056858

TA貢獻1803條經驗 獲得超6個贊

其他人在評論中解釋說您希望方法a()和b()成為實例方法而不是靜態方法,以便您可以操縱this.


為了擁有你想要的靜態鏈接,只有鏈中的第一個方法需要是靜態的。您可以調用返回實例的靜態方法create(),然后可以在該實例上調用鏈中的后續函數。這是一個簡單的例子:


class TestModel {

    constructor() {

        this.data = {};

    }

    static create() {

        return new TestModel();

    }

    a() {

        this.data.a = true;

        return this;

    }

    b() {

        this.data.b = true;

        return this;

    }

    final() {

        return this.data;

    }

}

console.log(TestModel.create().a().b().final()); // => {"a": true, "b": true}

console.log(TestModel.create().a().final()); // => {"a": true}

console.log(TestModel.create().b().final()); // => {"b": true}


查看完整回答
反對 回復 2023-05-11
  • 1 回答
  • 0 關注
  • 124 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號