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

标签 javascript

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

相关文章:

javascript - 在浏览器中流式传输音频的最佳选择,也适用于移动设备?

javascript - 同一对象内是否可以有一个objectType

javascript - 在 Highstock/Highcharts 中设置 rangeSelector 容器的背景颜色

javascript - 任务完成时 Node.js res.render

javascript - 使用 CSS 和 JS 的 Web 应用程序的 flex 菜单

javascript - 如何在vue js中获取输入类型中的预填充数据

javascript - 在 react-leaflet/es/context.js 中调用 createContext 失败

javascript - 如何让菜单默认打开?

javascript - 返回 false 不会阻止表单提交

javascript - Recharts 条形图 - 仅在堆叠条形图中的某些条形上有条件地显示标签