简体   繁体   English

Javascript静态方法链

[英]Javascript static method chaining

Can i chain static methods in javascript ?我可以在 javascript 中链接静态方法吗? here's what an example for what i am trying to do这是我正在尝试做的一个例子

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

then i want to be able to called the methods like this然后我希望能够调用这样的方法

const value = testModel.a().b()

Others have explained in the comments that you want the methods a() and b() to be instance methods rather than static methods so that you can manipulate the value of this .其他人在评论中解释说,您希望方法a()b()是实例方法而不是静态方法,以便您可以操作this的值。

In order to have the static chaining that you want, only the first method in the chain needs to be static.为了获得您想要的静态链接,只有链中的第一个方法需要是静态的。 You can call a static method like create() that returns an instance, and then subsequent functions in the chain can be called on that instance.您可以调用像create()这样返回实例的静态方法,然后可以在该实例上调用链中的后续函数。 Here's a simple example:这是一个简单的例子:

 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