如何从类外部访问类内部的方法

错误的人

关于班级文件,我有几个问题。我有以下课程

class CouchController {
constructor(couchbase, config) {
    // You may either pass couchbase and config as params, or import directly into the controller
    this.cluster = new couchbase.Cluster(config.cluster);
    this.cluster.authenticate(config.userid, config.password);
    this.bucket = cluster.openBucket(config.bucket);
    this.N1qlQuery = couchbase.N1qlQuery;
  }

        doSomeQuery(queryString, callback) {
              this.bucket.manager().createPrimaryIndex(function() {            
              this.bucket.query(
                this.N1qlQuery.fromString("SELECT * FROM bucketname WHERE $1 in interests LIMIT 1"),
                [queryString],
                callback(err, result)
              )     
            });
          }
  }

我的问题是如何从类文件外部访问doSomeQuery函数?内部没有访问函数的问题,但是我需要能够从外部调用它。我尝试过这样的事情

const CouchController = require("../controllers/CouchController")(couchbase, config)
let newTest = new CouchController

这样做newTest永远不会公开doSomeQuery方法。

还有方法的局限性是什么?它可以仅仅是一个简单的,还是可以异步使用诺言等?

从技术上讲

对于以下问题,您应该考虑2个主要问题。

  1. 首先将其正确导出。我不确定您是否要忽略此内容,但将类导出为供外部使用很重要require如果您希望获得技术详细信息,这是NodeJS导出文档
// common module default export
module.exports = class CouchController {
  constructor(couchbase, config) {
    // You may either pass couchbase and config as params, or import directly into the controller
    this.cluster = new couchbase.Cluster(config.cluster);
    this.cluster.authenticate(config.userid, config.password);
    this.bucket = cluster.openBucket(config.bucket);
    this.N1qlQuery = couchbase.N1qlQuery;
  }

        doSomeQuery(queryString, callback) {
              this.bucket.manager().createPrimaryIndex(function() {            
              this.bucket.query(
                this.N1qlQuery.fromString("SELECT * FROM bucketname WHERE $1 in interests LIMIT 1"),
                [queryString],
                callback(err, result)
              )     
            });
          }
  }
  1. 类的初始化略有错误。您可以在此处查看有关此文档您可以将需求和初始化更改为...
const CouchController = require('../controllers/CouchController');
const newTest = new CouchController(couchbase, config);

// now you can access the function :)
newTest.doSomeQuery("query it up", () => {
// here is your callback
})

如果您使用的是ES6模块或打字稿,则可以导出类似...

export default class CouchController {
  // ...
}

...并导入...

import CouchController from '../controllers/CouchController';

const newTest = new CouchController(couchbase, config);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章