gpt4 book ai didi

javascript - 如何在不调用链中的每个方法的情况下构建流畅的 api

转载 作者:行者123 更新时间:2023-11-30 20:44:55 25 4
gpt4 key购买 nike

在流体 API 中,如 Chalk's 中提供的 API它们使您能够将方法链接在一起。

chalk.red.bgYellow('字符串')

这些方法也可以单独使用:

chalk.red('字符串')

我们如何在没有括号的情况下将它们串在一起。我意识到每个方法都会返回带有所有这些属性和方法的对象。我只是不明白它们怎么既是方法又是方法,又是带有方法的对象。

我已经查看了 Chalk 的源代码,但目前有点超出我的能力范围。

最佳答案

我认为这可能与它的实现方式一致。本质上,您在内部成员对象上有 setter/getter 。这些更改该对象的状态,同时还返回构造函数本身。

然后我们将方法添加到构造函数的原型(prototype)对象(或通过 es6 类语法糖)来设置内部对象的状态,同时还在该对象上调用方法(log()例如)。这些方法还设置内部对象的状态。

这绝对可以更简洁,但我认为这就是在实践中实现此类功能的方式。

如果有人有任何想法,请告诉我。

One thing to note: Initially I was returning the chk object from within the constructor. Of course, this doesn't work because then we don't have a prototype object on our constructor function, meaning I cannot add methods to it. It's a case of continuously returning the constructor function, and accessing the internal object's state from the methods on the prototype.

const Chalk = function () {
const _this = this
this.chk = {
get red () {
this.color = 'red'
return _this
},
get blue () {
this.color = 'blue'
return _this
},
get bgYellow () {
this.bg = 'yellow'
return _this
},
get bgBlue () {
this.bg = 'blue'
return _this
},
log(msg) {
this.msg = msg
console.log(`color: ${this.color} \nbg: ${this.bg} \nmsg: ${this.msg}
`)
}
}
}

Chalk.prototype.red = function (msg) {
this.chk.color = 'red'
this.chk.log(msg)
}

Chalk.prototype.blue = function (msg) {
this.chk.color = 'blue'
this.chk.log(msg)
}

const chalk = new Chalk().chk

chalk.bgYellow.blue('test')

关于javascript - 如何在不调用链中的每个方法的情况下构建流畅的 api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48813197/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com