我有几个关于类文件的问题。我有以下类(class)
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 方法。
方法的局限性是什么?它只能是一个简单的,还是可以是异步的并使用 Promise 等?
最佳答案
对于以下问题,您应该考虑两件主要事情。
- 首先正确导出。我不确定您是否打算忽略这一点,但导出该类以作为
require
供外部使用非常重要。这是NodeJS exports documentation如果您想了解技术细节。
// 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)
)
});
}
}
- 类初始化稍有不正确。您可以查看有关此here的文档。您可以将您的要求和初始化更改为...
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 模块或 typescript ,您可以导出类似...
export default class CouchController {
// ...
}
...并导入类似...
import CouchController from '../controllers/CouchController';
const newTest = new CouchController(couchbase, config);
关于javascript - 如何从类外部访问类内部的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56365103/