簡體   English   中英

Javascript靜態方法鏈

[英]Javascript static method chaining

我可以在 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()

其他人在評論中解釋說,您希望方法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}

暫無
暫無

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

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