gpt4 book ai didi

javascript - 在函数中返回 "this"是否是使用方法创建对象的推荐模式?

转载 作者:行者123 更新时间:2023-12-05 08:08:27 25 4
gpt4 key购买 nike

我发现自己有时在某些特定情况下需要这种模式,但在阅读代码时并不经常看到它。我想知道这是否是推荐的模式,或者是否有更好/更常见的方法来完成同样的事情。也许有一种更现代的方法可以在 ES6 中做同样的事情?

例子:

const state = {}
const stubs = {}
const query = () => {

stubs.collection = sinon.stub().callsFake( (collection) => {
state.collection = collection
return this
})
stubs.orderBy = sinon.stub().callsFake( (orderBy, direction) => {
state.orderBy = orderBy
state.direction = direction
return this
})
stubs.limit = sinon.stub().callsFake( (limit) => {
state.limit = limit
return this
})
stubs.get = sinon.stub().callsFake( () => {
const query = state
state = {}
const data = getQuery(query, mockDb)
return data
})

this.collection = stubs.collection
this.orderBy = stubs.orderBy
this.limit = stubs.limit
this.get = stubs.get
return this
}
stubs.firestore = sinon.stub(firebase, 'firestore').get( () => query )

基本上我在这种情况下使用它的原因是我必须为 firebase 单元测试添加一个“查询”方法。它必须在像这样的链中工作 firebase.firestore().collection('users').orderBy('timestamp').limit(10).get()。我弄乱了大约 5 个小时,但找不到另一种可行的方法。

没有 stub 部分的例子是:

const query = () => {

this.collection = () => {/*something...*/ return this}
this.orderBy = () => {/*something...*/ return this}
this.limit = () => {/*something...*/ return this}
this.get = () => {/*something...*/ return this}
return this
}

如果我不需要 stub ,我不确定为什么我实际上需要写这样的东西,这只是一个例子,可以在没有 stub 部分的情况下更清楚地说明我在说什么。

最佳答案

更好的方法:

const query = () => {
return {
collection() => { /* Code */ }
orderBy() => { /* Code */ }
limit() => { /* Code */ }
get() => { /* Code */ }
}
}

以这种方式,而不是将方法写入 this 并在改变它时返回 this (也许,在浏览器中,this === window,在非严格模式下),您可以直接返回包含这些方法的对象,这些方法中使用的 this 给出查询函数返回的对象。

关于javascript - 在函数中返回 "this"是否是使用方法创建对象的推荐模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49695077/

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